Rayn D Rayn D - 2 months ago 8
Node.js Question

Using BB promise to create server with free port

When I run the create server & listen in my unit test some times I'm getting the following error:

EADDRINUSE,

Now I want to handle it by using module portscanner to find free port

I do it like this

var http = require('http');
var Promise = require('bluebird');
var portscanner = require('portscanner');

var server = http.createServer(function (req, res) {
if (req.url == '/fail') {
res.end("Failed");
} else {
res.writeHead(200, {"Content-Type": "text/plain"});
}
});

Promise.promisifyAll(server);

server.listenAsync(portscanner.findAPortNotInUse)

module.exports = server;


This was working but not sure if it's stable code

my question is if it's OK to use it like this? and this is not some dirty workaround and if yes how can I handle it better?

Answer

Not sure why you are using promise in this case, you can simply use something like :

portscanner.findAPortNotInUse(3000, 5000, '127.0.0.1', (error, port) =>{
    server.listen(port);
});