Chetan Motamarri
Chetan Motamarri

Reputation: 1244

When is JavaScript function expression invoked/executed/called in this following code?

var express = require('express')

var app = express();

app.use(express.static('static'));

var server = app.listen(3000, function() {
    var port = server.address().port;
    console.log("Started server at port", port);
});

I am beginner in JavaScript. Here in this code, we never called server(); explicitly but it is executing. Also it is not immediately invoked function expression. At what point of time does app.listen() really executed ?

Code obtained from: https://github.com/vasansr/react-tutorial-mern/blob/master/webapp.js

Upvotes: 2

Views: 142

Answers (4)

MartinMouritzen
MartinMouritzen

Reputation: 241

app.listen is executed the moment the line is reached.

var server = app.listen(3000, function() { ...

now the server listens for incoming connections on port 3000.

the 2nd parameter of the listen function is a callback, which will be called as soon as someone connects to port 3000 (which is the first parameter of the function).

Upvotes: 3

Marian Toader
Marian Toader

Reputation: 81

Server doesn't seem to get called anywhere. Also, I think that server is not a function, but an object(that is returned from app.listen function).

Upvotes: 0

Andrew Luhring
Andrew Luhring

Reputation: 1894

From the expressjs docs:

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.listen = function() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Upvotes: 2

Dmitry Efimenko
Dmitry Efimenko

Reputation: 11203

the server is not a function. It's a variable. function app.listen(...) is executed right there, on line 7. The result of it is assigned to the variable server.

app.listen() function has a callback method (second parameter). It's executed when app started listening. so to speak. When this callback is called server.address().port will return you server's port.

Upvotes: 0

Related Questions