Last active
April 19, 2024 11:51
-
-
Save timoxley/1689041 to your computer and use it in GitHub Desktop.
check if a port is being used with nodejs
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
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) | |
} |
I like to use this instead! :-)
Thanks. This is a very simple and easy to use package.
a promise implement
import { createServer } from "net";
const isPortTaken = (port: number, type: 'IPv4' | 'IPv6' = 'IPv4') => {
let hasError = 0;
return new Promise((res) => {
const server = createServer()
.once('error', err => { if (err) { res(false) } })
.once('listening', () => {
server
.once('close', () => {
hasError++;
if (hasError > 1) {
res(false)
} else {
res(true)
}
})
.close()
})
.listen(port, type === 'IPv4' ? '0.0.0.0' : '::')
})
};
Test without producing an error
on mac and most unix/linux
const { spawnSync } = require('child_process')
function checkPort(port) {
const output = spawnSync(
`lsof -i tcp:${port} | awk '{print $2}' |grep --invert PID`,
{ shell: true }
)
if (output.error) {
console.error(output.error)
return
}
const pid = Buffer.from(output.stdout.buffer).toString().split('\n')[0]
console.log({ pid })
return pid
}
const pid = checkPort(443))
if (pid) {
console.log(`server is running, process id ${pid}`)
}
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
Thnx man 😉