AeonZh
AeonZh

Reputation: 55

About nodejs server.listen()

I just started to learn about nodejs servers and websockets. Said I have this server written in javascript using socket.io and express.

var app = require('express')(),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    port = process.env.PORT || 8080;

Is there any difference between:

server.listen(port, function(){
    console.log("listening port " + port);
});

and

server.listen(port);
console.log("listening port " + port);

Apparently they work the same.

So what actually server.listen() do?

Upvotes: 5

Views: 10481

Answers (1)

Josh Beam
Josh Beam

Reputation: 19772

According to the docs for server.listen:

This function is asynchronous. When the server has been bound, 'listening' event will be emitted.

It uses a callback because the log statement inside the callback is a confirmation that the port has been bound.

Apparently they work the same.

Incorrect. If you log outside of the callback, sure, it'll still log the port number, but this happens in parallel of the actual bounding of the port, and you don't know whether or not it was successful.

Upvotes: 5

Related Questions