Created
October 2, 2020 15:53
-
-
Save dkarmalita/f97254aafd426ae4df56b7dd46cbd0ea to your computer and use it in GitHub Desktop.
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
const net = require('net'); | |
const isPortOpen = async (port, { timeout = 1000, host } = {}) => { | |
const promise = new Promise(((resolve, reject) => { | |
const socket = new net.Socket(); | |
const onError = () => { | |
socket.destroy(); | |
reject(); | |
}; | |
socket.setTimeout(timeout); | |
socket.once('error', onError); | |
socket.once('timeout', onError); | |
socket.connect(port, host, () => { | |
socket.end(); | |
resolve(); | |
}); | |
})); | |
try { | |
await promise; | |
return false; | |
} catch (_) { | |
return true; | |
} | |
}; | |
const findOpenPort = async (port) => { | |
const isOpen = await isPortOpen(port); | |
if (isOpen) { return port; } | |
return findPort(port + 1); | |
}; | |
module.exports = findOpenPort; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment