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

Why do you need to only include the port number (3000) but not the hostname?

Andrew says that it will listen to what's out there 'naturally' if you leave out the hostname:

var http, hostname, port, server;

http = require('http');

hostname = 'localhost';
port = 8000;

server = http.createServer(function (request, response) {
  response.statusCode = 200;
  response.setHeader('Content-Type', 'text/plain');
  response.end('Hello there\n');
});

server.listen(port, hostname, function () {
  console.log('Server running at http://' + hostname + ':' + port + '/');
});

How does that work then? I looked in the docs, but there was nothing I could see...very confused lol

It really depends on your hosting situation. In most real-world hosting scenarios, people won't really be accessing your node app directly. Instead, you'd bind it to localhost only, use an available port and then use a web server as a proxy (through Phusion Passenger or nginx).

If you are unable to do this for some reason, then you'd bind it to the IP address of the network interface that is connecting your server to the Internet.

2 Answers

The hostname is optional because by default, connections are being accepted on any address available. In most scenarios, you can safely omit it and it'll work just fine. Specifying the address is for situations where you have multiple network devices and you want to make the application available on only one network (and similar).

You can read more about that in the Node.js documentation.

Set it to the ip of the host provider you mean?

ok, so if I was making this site live, I could just leave off the hostname and it will work?

It is best to set it, just in case, but it should be fine if you leave it out.