Sometimes you need to open a random port on your node server. You can of course try a random one to see if it fails, but a npm module makes this easy:
npm install portfinder
var pf = require('portfinder'); var http = require('http'); // If you want to change the first port to check pf.basePort = 9000; // default is 8000 pf.getPort(function(err, port) { if (err) return; // handle error http.createServer().listen(port); console.log("I'm now listening on port "+port); });
More information about the module is found at npmjs.com
Recent Comments