Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About app.listen() callback

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().

like image 428
Okem Avatar asked Oct 19 '15 19:10

Okem


People also ask

What does the app listen method do?

The app. listen() function is used to bind and listen the connections on the specified host and port. This method is identical to Node's http. Server.

What does the listen () function do in node JS?

listen() method creates a listener on the specified port or path.

What is App listen Express JS?

Express JSServer Side ProgrammingProgramming. The app. listen() method binds itself with the specified host and port to bind and listen for any connections. If the port is not defined or 0, an arbitrary unused port will be assigned by the operating system that is mainly used for automated tasks like testing, etc.

What is app get in node JS?

The app. get() function routes the HTTP GET Requests to the path which is being specified with the specified callback functions. Basically it is intended for binding the middleware to your application. Syntax: app.get( path, callback )


1 Answers

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...

like image 152
DontVoteMeDown Avatar answered Sep 22 '22 11:09

DontVoteMeDown