当我的 Express.js 时,我需要做一些有用的事情。服务被 SIGINT
停止。使用 Express.js 版本 3.0.6,我知道这应该可以工作:
var express = require('express');
var app = express();
var server = app.listen(3000);
process.on('SIGINT', function() {
console.log('Do something useful here.');
server.close();
});
但除非我发出 SIGINT
(Control-C) 两次,否则该过程不会返回 Bash 提示:
$ node problem.js
^CDo something useful here.
^CDo something useful here.
net.js:1046
throw new Error('Not running');
^
Error: Not running
at Server.close (net.js:1046:11)
at process.<anonymous> (/path/to/problem.js:8:10)
at process.EventEmitter.emit (events.js:93:17)
at SignalWatcher.startup.processSignalHandlers.process.on.process.addListener.w.callback (node.js:486:45)
$
还有一个警告。如果我启动这个 Express.js 服务并且不发送任何请求,那么 SIGINT
会正确终止。
显然我在这里缺少一些基本的东西?
最佳答案
通过捕获 SIGINT
处理程序,您可以防止 默认行为,即退出进程。当您第二次使用 Ctrl+C
时,进程会终止,因为 server.close
会抛出未捕获的异常。
只需在 SIGINT
处理程序的末尾添加一个 process.exit()
即可正常退出进程。
关于node.js - 如何使用 Express.js 正确处理 SIGINT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14372288/