Ping a server from a grunt task

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:

Shell

1

npm install tcp-ping

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

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

varserver={

address:'localhost',

port:8080

}

// simple task to check that a server is up & running

grunt.registerTask('ping-server','Ping a server server',function(){

vardone=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:

JavaScript

1

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

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