Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a Simple Dynamic Site with Node.js Creating a Simple Server in Node.js Creating a Simple Server

Can't create webserver

I try to do this code below to create a webserver. When I write node app.js in the console it, should say Hello world. But this comes up:

Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3

My code:

var http = require('http'); http.createServer(function (request, response) { response.writeHead(200; {'Content-Type', 'text/plain'}); response.end('Hello World\n'); })listen(3000); console.log(Server running at http://<workspace-url>/);

2 Answers

Ben Slivinn
Ben Slivinn
10,156 Points
node.js
var http = require('http');
http.createServer(function (request,response)
  {
    response.writeHead(200 {'Content-Type', 'text/plain'});
    response.end('Hello World\n'); 
  }
);
listen(3000);
console.log(Server running at http://<workspace-url>/);

your code can't find "listen(3000)" method. you should assign "http.createServer" to a variable, and call "listen(3000)" from the variable.

Correct:

node.js
var http = require('http');
var server = http.createServer(function (request,response)
  {
    response.writeHead(200 {'Content-Type', 'text/plain'});
    response.end('Hello World\n'); 
  }
);
server.listen(3000);
console.log(Server running at http://<workspace-url>/);

Or Nodejs preferred way (using ES6)(Advanced Way);

node.js
const http = require('http');
const hostname = "http://<workspace-url>/"
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at ${hostname}:${port}/`);
});

Happy Coding!

great thanks!!