Skip to content

Instantly share code, notes, and snippets.

@joeyjiron06
Created December 22, 2021 18:58
Show Gist options
  • Save joeyjiron06/79907d912b00d2cf12194deeb24d6597 to your computer and use it in GitHub Desktop.
Save joeyjiron06/79907d912b00d2cf12194deeb24d6597 to your computer and use it in GitHub Desktop.
Ping an address and get a promise result back

Ping (Node JS)

Ping a simple tcp socket and return a promise that let's you konw if the address is a alive or not.

import net from 'net';
/**
* @param {string} address
* @param {number} port
* @param {number} [timeoutMs=3000]
* @returns {Promise<boolean>}
*/
function ping(address, port, timeoutMs = 3000) {
return new Promise((resolve) => {
const socket = new net.Socket();
/**
* @param {boolean} isAlive
*/
function finish(isAlive) {
resolve(isAlive);
socket.destroy();
}
socket.connect(port, address, () => {
finish(true);
});
socket.on('error', () => {
finish(false);
});
socket.setTimeout(timeoutMs, () => {
finish(false);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment