Skip to content

Instantly share code, notes, and snippets.

@Trott
Created January 14, 2019 04:29
Show Gist options
  • Save Trott/4caed3e2ce93a92318ec1d54aedbbc80 to your computer and use it in GitHub Desktop.
Save Trott/4caed3e2ce93a92318ec1d54aedbbc80 to your computer and use it in GitHub Desktop.
Only assigns available ports
// Testing for macOS, which supplies available ports sequentially.
var net = require('net');
createServer(0, function () {
var port = this.address().port;
console.log('server was assigned port ' + port);
createServer(port+1, function () {
var port = this.address().port;
console.log('server was assigned port ' + port);
createServer(0, function () {
var port = this.address().port;
// This line will show that the OS skipped the occupied port and assigned the next available port.
console.log('server was assigned port ' + port);
});
});
});
function createServer(port, callback) {
console.log('create server with port ' + port);
var server = net.createServer();
server.listen(port, callback).unref();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment