Grunt task to wait for exit

 ̄綄美尐妖づ 提交于 2019-12-23 17:03:38

问题


I've got a task that starts IIS Express async, and to stop IIS I have to fire a grunt event.

I would like to make a task that just waits until i press ctrl-c and then fires that event.

I've tried doing this:

grunt.registerTask("killiis", function(){
    process.stdin.resume();
    var done = this.async();
    grunt.log.writeln('Waiting...');    

    process.on('SIGINT', function() {
        grunt.event.emit('iis.kill');
        grunt.log.writeln('Got SIGINT.  Press Control-D to exit.');
        done();
    });
});

The task stops grunt successfully, but doesn't send the event properly.


回答1:


SIGINT handlers work in Node.js, but not in Grunt (I don't know why). I handle ctrl+c manually using readline module and listen to exit event:

var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.on('SIGINT', function() {
  process.emit('SIGINT');
});

process.on('exit', killIis);

function killIis() {
  // kill it
}

Additionally I suggest to listen to SIGINT, SIGHUP and SIGBREAK signals to handle console window close or ctrl+break (if anybody use it, heh). Call process.exit() in these handlers when you also want to stop the app:

process.on('exit', killIis);
process.on('SIGINT', killIisAndExit);
process.on('SIGHUP', killIisAndExit);
process.on('SIGBREAK', killIisAndExit);

I have a fork of grunt-iisexpress that kills IIS on exit: https://github.com/whyleee/grunt-iisexpress.




回答2:


I tried whyleee's suggestion, but I found that grunt wasn't waiting for the cleanup process to exit before shutting itself down.

The solution for me was based on this article .

module.exports = function(grunt) {
  var exec, readline, shuttingDown, stdInterface;
  shuttingDown = false;
  readline = require("readline");
  exec = require("child_process").exec;
  // other grunt requires / task loads, including a "cleanup" task ...
  stdInterface = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  stdInterface.on("SIGINT", function() {
    var child;
    if (shuttingDown) {
      return;
    }
    shuttingDown = true;
    console.info("Cleaning up ...");
    child = exec("grunt cleanup", function(err, stdout, stderr) {
      console.info(stdout);
      process.exit(err ? 1 : 0);
    });
  });
  // other grunt config ...
};


来源:https://stackoverflow.com/questions/21922443/grunt-task-to-wait-for-exit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!