我正在按照这里的指导(监听SIGINT事件)来优雅地关闭我的Windows-8托管的node.js应用程序以响应Ctrl-C或服务器关闭.
但Windows没有SIGINT.我也试过process.on('exit'),但似乎迟到做任何有成效的事情.
在Windows上,这段代码告诉我:错误:没有这样的模块
process.on( 'SIGINT', function() {
console.log( "\ngracefully shutting down from SIGINT (Crtl-C)" )
// wish this worked on Windows
process.exit( )
})
Run Code Online (Sandbox Code Playgroud)
在Windows上,此代码运行,但为时已晚,无法做任何优雅的事情:
process.on( 'exit', function() {
console.log( "never see this log message" )
})
Run Code Online (Sandbox Code Playgroud)
SIGINTWindows上有同等的事件吗?
Gab*_*mas 137
您必须使用readline模块并侦听SIGINT事件:
http://nodejs.org/api/readline.html#readline_event_sigint
if (process.platform === "win32") {
var rl = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
rl.on("SIGINT", function () {
process.emit("SIGINT");
});
}
process.on("SIGINT", function () {
//graceful shutdown
process.exit();
});
Run Code Online (Sandbox Code Playgroud)
除非您需要为其他任务导入"readline",否则我建议在程序验证它在Windows上运行后导入"readline".此外,对于那些可能不知道的人 - 这适用于Windows 32位和Windows 64位系统(将返回关键字"win32").感谢Gabriel这个解决方案.
if (process.platform === "win32") {
require("readline")
.createInterface({
input: process.stdin,
output: process.stdout
})
.on("SIGINT", function () {
process.emit("SIGINT");
});
}
process.on("SIGINT", function () {
// graceful shutdown
process.exit();
});
Run Code Online (Sandbox Code Playgroud)
现在它只适用 于所有平台,包括 Windows。
以下代码记录然后在 Windows 10 上正确终止:
process.on('SIGINT', () => {
console.log("Terminating...");
process.exit(0);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22289 次 |
| 最近记录: |