Use grunt to restart phantomjs process

I use grunt to do some tasks every time I change my code (like jshint) and I want to restart the phantomJs process every time I have changes.

The first way I found is to use grunt.util.spawn to launch phantomJs for the first time.

// http://gruntjs.com/api/grunt.util#grunt.util.spawn var phantomJS_child = grunt.util.spawn({ cmd: './phantomjs-1.9.1-linux-x86_64/bin/phantomjs', args: ['./phantomWorker.js'] }, function(){ console.log('phantomjs done!'); // we never get here... }); 

And then, every time the clock restarts, another task uses grunt.util.spawn to kill the phantomJs process, which, of course, is VERY ugly.

Is there a better way to do this? The fact is that the phantomJs process is not thematic, because I use it as a web server for a REST API server with JSON.

Can I have a callback or something else when the clock fires, so I can close my previous phantomJs process before starting the task again to create a new one?

I used grunt.event to create a handler, but I don’t see how to access the phantomjs process to kill it.

 grunt.registerTask('onWatchEvent',function(){ // whenever watch starts, do this... grunt.event.on('watch',function(event, file, task){ grunt.log.writeln('\n' + event + ' ' + file + ' | running-> ' + task); }); }); 
+4
source share
1 answer

This completely untested code may be the solution to your problem.

The Node function of the non-resident child exec immediately returns a reference to the child process, which we can save in order to kill it later. To use it, we can create a custom grunt task on the fly, for example:

 // THIS DOESN'T WORK. phantomjs is undefined every time the watcher re-executes the task var exec = require('child_process').exec, phantomjs; grunt.registerTask('spawn-phantomjs', function() { // if there already phantomjs instance tell it to quit phantomjs && phantomjs.kill(); // (re-)start phantomjs phantomjs = exec('./phantomjs-1.9.1-linux-x86_64/bin/phantomjs ./phantomWorker.js', function (err, stdout, stderr) { grunt.log.write(stdout); grunt.log.error(stderr); if (err !== null) { grunt.log.error('exec error: ' + err); } }); // when grunt exits, make sure phantomjs quits too process.on('exit', function() { grunt.log.writeln('killing child...'); phantomjs.kill(); }); }); 
0
source

Source: https://habr.com/ru/post/1498736/


All Articles