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

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
217,576 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