Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!!