4

コードを変更するたびにいくつかのタスクを実行するために grunt を使用しています (たとえば jshint )。変更があるたびに 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 プロセスが終了していないことです。これは、JSON を使用して REST API を提供するための Web サーバーとして使用しているためです。

タスクを再実行して新しいプロセスを作成する前に、以前の 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); 
    });
});
4

1 に答える 1

0

この完全にテストされていないコードは、問題の解決策になる可能性があります。

ノードのネイティブの子生成関数execは、すぐに子プロセスへの参照を返します。これを保持して、後でそれを強制終了できます。それを使用するために、次のようにその場でカスタム grunt タスクを作成できます。

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

});
于 2013-08-24T17:17:34.660 に答える