Ping a simple tcp socket and return a promise that let's you konw if the address is a alive or not.
Created
December 22, 2021 18:58
-
-
Save joeyjiron06/79907d912b00d2cf12194deeb24d6597 to your computer and use it in GitHub Desktop.
Ping an address and get a promise result back
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
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