Skip to main content

Get an available port in node.js.

var net = require('net');

var getPort = function (cb) {
  var server = net.createServer();
  server.unref();
  server.on('error', cb);
  server.listen(0, function () {
    server.close(cb.bind(null, null, server.address().port));
  });
};


//
// usage
// 

getPort(function (err, port) {
  console.log(port);
});