Created
January 14, 2019 04:29
-
-
Save Trott/4caed3e2ce93a92318ec1d54aedbbc80 to your computer and use it in GitHub Desktop.
Only assigns available ports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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