Last updated: Apr 5, 2024
Reading time·5 min
ping
package to ping a remote server in Node.jsTo ping a URL or a remote IP address using Node.js:
child_process.exec()
method to spawn a shell that executes a given
command.import child_process from 'child_process'; import util from 'util'; const exec = util.promisify(child_process.exec); async function ping(hostname) { try { const {stdout, stderr} = await exec(`ping -c 3 ${hostname}`); console.log('stderr: ', stderr); console.log('stdout: ', stdout); } catch (err) { console.log(err); } } ping('www.google.com');
The code sample above uses the
ES6 import/export syntax,
however, you can also use the CommonJS require()
syntax.
const child_process = require('child_process'); const util = require('util'); const exec = util.promisify(child_process.exec); async function ping(hostname) { try { const {stdout, stderr} = await exec(`ping -c 3 ${hostname}`); console.log('stderr: ', stderr); console.log('stdout: ', stdout); } catch (err) { console.log(err); } } ping('www.google.com');
Note that the examples use the ping
command from the underlying system.
If you don't have ping
installed, you can either install the module before you
run the code snippet or use the approach from the next subheading.
The util.promisify() method takes a function that follows the common error-first callback style and returns a version that returns a Promise.
const exec = util.promisify(child_process.exec);
The child_process.exec() method spawns a shell and executes the given command within the shell, buffering any generated output.
const {stdout, stderr} = await exec(`ping -c 3 ${hostname}`);
The command string that you pass to the exec()
function is processed directly
by the shell, so special characters have to be escaped with a backslash \
.
The command in the example pings the specified remote host 3 times but you can adjust this accordingly.
You can also omit the www.
subdomain when issuing the command.
// ✅ Works const {stdout, stderr} = await exec('ping -c 3 google.com');
However, make sure you don't specify the protocol scheme (e.g. http://
or
https://
).
// ⛔️ Does NOT work const {stdout, stderr} = await exec('ping -c 3 https://google.com');
The code sample above produces the following error.
Error: Command failed: ping -c 3 https://google.com ping: https://google.com: Name or service not known
ping
package to ping a remote server in Node.jsYou can also use the ping package to ping a remote server or an IP address in Node.js.
In case you don't have a package.json
file, run the following command.
npm init -y
Open your terminal in your project's root directory (where your pacakge.json
file is) and run the following command to install ping
.
# with NPM npm install ping # or with YARN yarn add ping
Here is a simple example that pings 3 hosts.
import ping from 'ping'; // 👇️ Use this import if you use CommonJS require() // const ping = require('ping'); const hosts = ['192.168.1.1', 'google.com', 'yahoo.com']; async function example() { for (const host of hosts) { const response = await ping.promise.probe(host); console.log(response); } } example();
The ping.promise.probe()
method takes a hostname or an IP address and a
configurations object.
Here is an example that also passes the configurations object.
import ping from 'ping'; const hosts = ['192.168.1.1', 'google.com', 'yahoo.com']; async function example() { for (const host of hosts) { const config = { timeout: 10, // WARNING: -i 2 argument may not work in other platforms like windows extra: ['-i', '3'], }; const response = await ping.promise.probe(host, config); console.log(response); } } example();
The timeout
configuration property is the timeout in seconds for each ping
request.
Note that the -i 2
argument may not work on Windows.
The same approach can be used if you need to check if a single host is online.
import ping from 'ping'; async function example(host) { const config = { timeout: 10, // WARNING: -i 2 argument may not work in other platforms such as Windows extra: ['-i', '3'], }; const response = await ping.promise.probe(host, config); console.log(response); } example('google.com');
Here is an example that tests if multiple hosts are online using callbacks
instead of async/await
.
import ping from 'ping'; // 👇️ Use this import if you use CommonJS require() // const ping = require('ping'); const hosts = ['192.168.1.1', 'google.com', 'yahoo.com']; hosts.forEach(host => { ping.sys.probe(host, function (isAlive) { const message = isAlive ? 'host ' + host + ' is online' : 'host ' + host + ' is OFFLINE'; console.log(message); }); });
The code sample checks if the 3 hosts in the URL are online or offline.
You can also pass a configuration object as the second argument to the
ping.sys.probe()
method.
import ping from 'ping'; // 👇️ Use this import if you use CommonJS require() // const ping = require('ping'); const hosts = ['192.168.1.1', 'google.com', 'yahoo.com']; const config = { timeout: 10, // WARNING: -i 2 may not work in other platforms like windows extra: ['-i', '3'], }; hosts.forEach(host => { ping.sys.probe( host, function (isAlive) { const message = isAlive ? 'host ' + host + ' is online' : 'host ' + host + ' is OFFLINE'; console.log(message); }, config, ); });
We passed the following 3 arguments to the ping.sys.probe()
method:
The callback function gets called with 3 arguments:
isAlive
- whether the ping request was successful.error
- an error object or null
if no error occurred.The code sample above checks if 3 hosts are online, however, the same approach can be used to check if a single host is online.
import ping from 'ping'; // 👇️ Use this import if you use CommonJS require() // const ping = require('ping'); const config = { timeout: 10, // WARNING: -i 2 may not work in other platforms such as Windows extra: ['-i', '3'], }; const host = 'google.com'; ping.sys.probe( host, function (isAlive) { const message = isAlive ? 'host ' + host + ' is online' : 'host ' + host + ' is OFFLINE'; console.log(message); }, config, );
You can view more examples of using the ping
module in the
usage section of the package's NPM page.
You can learn more about the related topics by checking out the following tutorials: