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

Port showing as undefined even though it's defined

When editing the node.js server code to replicate the example in the video, by removing the hostname parameter this is what happens

Code

const http = require('http');

const port = 3000;

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

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

Console Result

Server running at http://undefined/

1 Answer

Steven Parker
Steven Parker
231,248 Points

The "listen" method typically takes a port number as an argument (and an optional callback function), but this code is passing it only a callback function. The fact that the callback parameter is named "port" is not important, particularly since the "listen" method doesn't provide any argument to the callback (thus the "undefined" in the message).

As for the actual port number, the documentation says:

If port is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using server.address().port after the 'listening' event has been emitted.

Ohhhh right. After reading this 'The "listen" method typically takes a port number as an argument (and an optional callback function), but this code is passing it only a callback function' I got it right away and it's sorted :)

Thank you!

I find it really hard to understand documentation