Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 834
AeonZh Avatar asked Feb 12 '16 17:02

AeonZh


1 Answers

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.

like image 103
Josh Beam Avatar answered Oct 08 '22 10:10

Josh Beam