如何正确结束gulp任务

时间:2016-09-19 06:08:34

标签: gulp

我正在尝试编写gulp任务来执行程序并等待按任何键以退出程序。

到目前为止,我有这个:

gulp.task('runDevelopment', function (done) {
  console.log('\n\n---\nPress any key to exit\n---\n');

  var api = spawn('node', ['node_modules/api-gateway-server/server.js', 'etc/swagger.yaml']);
  api.stdout.on('data', function (data) {
    console.log(data.toString());
  });
  api.stderr.on('data', function (data) {
    console.log(data.toString());
  });

  process.stdin.on('data', function () {
    api.kill('SIGKILL');
    done();
  });
});

这会运行程序,并按预期杀死它,但gulp永远不会退出。我在控制台中看到了这一点:

20:04 $ gulp
[20:06:54] Using gulpfile ~/Development/swiki/gulpfile.js
[20:06:54] Starting 'documentCopy'...
[20:06:54] Starting 'documentZip'...
[20:06:54] Starting 'runDevelopment'...


---
Press any key to exit
---

[20:06:54] Finished 'documentCopy' after 52 ms
[20:06:54] Finished 'documentZip' after 41 ms
[20:06:54] Starting 'package'...
[20:06:54] Finished 'package' after 4.9 μs
API Gateway server listening on port 7111

[20:06:57] Finished 'runDevelopment' after 3.06 s
[20:06:57] Starting 'run'...
[20:06:57] Finished 'run' after 2.72 μs
[20:06:57] Starting 'default'...
[20:06:57] Finished 'default' after 1.16 μs
Terminated: 15
✘-TERM ~/Development/swiki [master|…6] 
20:07 $ 
只有在我Terminated: 15的另一个终端后,才会给我killall gulp

如何让它正常工作?

1 个答案:

答案 0 :(得分:2)

问题是您通过发送SIGKILL成功终止子进程,但您仍在侦听父进程的process.stdin上的传入数据。只要您这样做,父进程就不会退出。

您必须通过致电stream.pause()明确告诉process.stdin不再发出'data'个事件:

process.stdin.on('data', function () {
  process.stdin.pause();
  api.kill('SIGKILL');
  done();
});

如果其他所有方法都失败了,您也可以拨打process.exit()作为最后的手段:

process.stdin.on('data', function () {
  api.kill('SIGKILL');
  done();
  process.exit(0);
});