29

I'm new in javascript and now i'm learn about express.js, but i get some code that makes me confused about how they work. I was tring to figure out how this code work but i still don't get it:

var server = app.listen(3000, function (){
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

My question is how this anonymous function can using the server variable, when the server variable getting return value from app.listen().

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
Okem
  • 395
  • 1
  • 4
  • 12

1 Answers1

34

The anonymous function is in fact a callback which is called after the app initialization. Check this doc(app.listen() is the same as server.listen()):

This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event.

So the method app.listen() returns an object to var server but it doesn't called the callback yet. That is why the server variable is available inside the callback, it is created before the callback function is called.

To make things more clear, try this test:

console.log("Calling app.listen().");

var server = app.listen(3000, function (){
  console.log("Calling app.listen's callback function.");
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

console.log("app.listen() executed.");

You should see these logs in your node's console:

Calling app.listen().

app.listen() executed.

Calling app.listen's callback function.

Example app listening at...

Community
  • 1
  • 1
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105