Skip to content

Instantly share code, notes, and snippets.

@dkarmalita
Created October 2, 2020 15:53
Show Gist options
  • Save dkarmalita/f97254aafd426ae4df56b7dd46cbd0ea to your computer and use it in GitHub Desktop.
Save dkarmalita/f97254aafd426ae4df56b7dd46cbd0ea to your computer and use it in GitHub Desktop.
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