Ping a server from a grunt task

  • Post by Nicolas Ramz
  • Feb 27, 2015
Ping a server from a grunt task

I was working on a small project that sets up a proxy using grunt, and then starts a node server. Problem is that if the proxy wasn’t up and running, grunt would still start the server and any call to the proxy would make the grunt server crash with some unrelated error.

I decided to add a simple task that would ping the proxy server, and simply fail with an explicit error if it wasn’t responding.

I found lots of different node modules but most of them were simple wrappers to the ping command line: that wasn’t very useful, especially since I wanted something portable.

Then I found tcp-ping which attempts to contact any server, on any port at tcp-level which is not only much faster than traditionnal ping but allows to test any service and not the whole connection.

After installing the module like any other node module:

npm install tcp-ping

In a few minutes I came up with this little task:

var server = {
    address: 'localhost',
    port: 8080
}
// simple task to check that a server is up & running
grunt.registerTask('ping-server', 'Ping a server server', function() {
    var done = this.async(),
        tcpp = require('tcp-ping');

    tcpp.ping({
        address: server.address,
        port: server.port,
        attempts: 1,
        timeout: 1
    }, function(err, data) {
        grunt.log.writeln('Attempt to ping server at port: ' + server.port);
        if (err || isNaN(data.avg)) {
            grunt.log.error('Server does not respond: is it running?');
            done(false);
        } else {
            grunt.log.ok('Server is responding!');
            done(true)
        }
    });
});

As you can see this is quite easy. To be sure your task prevents your server from running if the proxy isn’t there you can simply call the task before the connect task:

 grunt.task.run(['ping-server', 'connect:dist:keepalive']);

If your server isn’t running, you will end up with the following explicit error:

Running "ping-server" task
Attempt to ping server at port: 8082
>> Server does not respond: is it running?