2013-08-24 53 views
4

我使用grunt在每次更改我的代码时都完成了一些任务(例如jshint),并且我希望每次更改时都重新加载phantomJs进程。使用grunt重新启动phantomjs进程

我发现的第一种方法是使用grunt.util.spawn首次运行phantomJs。

// 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... 
}); 

然后,每次重新启动手表,另一个任务使用grunt.util.spawn杀phantomJs过程,这当然是非常难看。

有没有更好的方法来做到这一点? 问题是phantomJs进程没有被终止,因为我使用它作为web服务器来使用JSON来服务REST API。

当我重新运行任务以创建一个新任务之前,我是否可以收到一个咕噜声回调或什么时候开始观看,因此我可以关闭以前的phantomJs过程?

我用grunt.event来创建一个处理程序,但我看不到如何访问phantomjs进程以杀死它。

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); 
    }); 
}); 

回答

0

完全未经测试代码可能是你的问题的解决方案。

节点的本地子产卵函数exec立即返回对子进程的引用,我们可以继续引用它以稍后将其杀死。要使用它,我们可以立即创建一个自定义的咕噜任务,如下所示:

// 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's 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

我只是在使用它之前先熟练地熟悉它。通过这种方式,我们再次手动杀死该进程。我不知道我们可以像这样使用“退出”事件。你确定每当观看重新加载任务时,这个'退出'事件会触发?当然,在'退出'上杀死它是最好的例子。 – AntouanK

+0

对不起,我把你的用例与我在另一个选项卡上阅读的东西混淆了。只是对代码片段进行了一些编辑,我认为会与您的用例相匹配。但它不起作用。每当观察者检测到更改时,都会重新执行Gruntfile.js。因此没有持续参考phantomjs是可能的。反正也不是这样。 –