NodeJS 应用程序中的 SIGINT 处理程序未调用 ctrl-C (Mac)

Eri*_*sen 3 javascript node.js

我的代码:

process.on('SIGINT', function() {
  console.log('Interrupted');
  process.exit();
});

// A big loop here that takes several seconds to execute through.

console.log('Exited without interruption');
Run Code Online (Sandbox Code Playgroud)

我从命令行运行该程序,当它仍在运行时,按ctrl+ C。我立即返回到命令行。但是,console.log('Interrupted')不会显示在输出中。一段时间后,显示 ,证明当我点击+console.log('Exited without interruption')时该进程并没有退出,而是在我返回到命令行后继续在后台运行。ctrlC

删除该process.on()语句允许进程在按ctrl+时退出。C(不输出“无中断退出”。)

尝试了() => {function() {函数声明样式,结果相同。

模组们,请不要太匆忙地将其标记为重复项,当然,我很高兴能参考现有的可行解决方案。我见过Can't stop local node server with Ctrl + C (Mac) - 响应ctrl+的行为C是不同的。

Art*_* P. 8

// Begin reading from stdin so the process does not exit imidiately
process.stdin.resume();
process.on('SIGINT', function() {
  console.log('Interrupted');
  process.exit();
});
Run Code Online (Sandbox Code Playgroud)

https://nodejs.org/api/process.html#process_signal_events

编辑:

// 这里有一个大循环,需要几秒钟才能执行完。

这是你的问题。NodeJS 是单线程的。当您执行同步循环时,您会阻止事件循环,并且其他事件侦听器将无法同时工作。

你可以:

  1. 使循环异步(带有 process.nextTick() 的递归函数)
  2. 为循环作业生成子进程(工作进程),然后主事件循环将不会被阻塞