Skip to content

Instantly share code, notes, and snippets.

@timoxley
Last active April 19, 2024 11:51
check if a port is being used with nodejs
var isPortTaken = function(port, fn) {
var net = require('net')
var tester = net.createServer()
.once('error', function (err) {
if (err.code != 'EADDRINUSE') return fn(err)
fn(null, true)
})
.once('listening', function() {
tester.once('close', function() { fn(null, false) })
.close()
})
.listen(port)
}
@ffd8
Copy link

ffd8 commented Feb 22, 2024

const pid = checkPort(443)) 

@tysonrm – nice technique! FYI, there's an extra ) when making the checkPort() example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment