An anonymous function is actually a callback that is called after application initialization. Check this document ( app.listen() same as server.listen() ) :
This function is asynchronous. The last parameter callback will be added as a listener for the listen event.
Thus, the app.listen() method returns a var server object, but it has not yet called a callback. This is why the server variable is available inside the callback; it is created before the callback function is called.
To make things clearer, try this test:
console.log("Calling app.listen()."); var server = app.listen(3000, function (){ console.log("Calling app.listen 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 the node console:
Call app.listen ().
Performedapp.listen ().
Calling the callback function app.listen.
An example of listening to an application ...
source share