Node.js 处理信号事件
Signals 是一个 POSIX(便携式操作系统接口)互通系统。这些事件将在 Node 接收到信号事件时发出。为了通知事件已发生,发送通知。
信号处理程序将接收信号的名称,信号名称根据每个事件的名称为大写(例如 SIGTERM 信号的“SIGTERM”)。
句法:
process.on(signalName, callback);
参数:此函数接受以下参数:
- signalName:这是我们要为其调用信号的信号名称。
- callback : 执行的回调函数。
示例 1: SIGINT 事件
通过终端在所有平台上都支持它,通常使用Ctrl+C生成(您也可以更改它)。启用终端原始模式并使用 Ctrl+C 时不会生成它。这里,文件名是 index.js。
Javascript
process.stdin.resume();
// If SIGINT process is called then this will
// run first then the next line
process.on('SIGINT', () => {
console.log('Hey Boss I just Received SIGINT.');
});
// We are using this single function to handle multiple signals
function handle(signal) {
console.log(`So the signal which I have Received is: ${signal}`);
}
process.on('SIGINT', handle);
Javascript
// Requiring module
const express = require('express')
const exp = express()
exp.get('/', (req, res) => {
res.send('Hello Sir')
})
const server = exp.listen(3000, () => console.log('Server ready'))
// Is delivered on Windows when Ctrl+Break is pressed.
// On non-Windows platforms, it can be listened on, but there
// is no way to send or generate it.
process.on('SIGBREAK', () => {
server.close(() => {
console.log('SIGNAL BREAK RECEIVED')
})
})
使用以下命令运行index.js文件:
node index.js
输出:按ctrl + c键,控制台屏幕上的输出如下:
Hey Boss I just Received SIGINT.
So the signal which I have Received is: SIGINT
示例 2: SIGBREAK 事件
这里,文件名是 index.js。
Javascript
// Requiring module
const express = require('express')
const exp = express()
exp.get('/', (req, res) => {
res.send('Hello Sir')
})
const server = exp.listen(3000, () => console.log('Server ready'))
// Is delivered on Windows when Ctrl+Break is pressed.
// On non-Windows platforms, it can be listened on, but there
// is no way to send or generate it.
process.on('SIGBREAK', () => {
server.close(() => {
console.log('SIGNAL BREAK RECEIVED')
})
})
使用以下命令运行index.js文件:
node index.js
输出:按ctrl + break生成信号键:
Server ready
SIGNAL BREAK RECEIVED
注意:您可以尝试SIGKILL信号,该信号告诉进程立即关闭并作为process.exit()工作。您可以将其用作语法process.kill(process.pid, 'SIGTERM')
SIGTERM: SIGTERM 信号被发送到 Node.js 的进程以请求其终止。它与 SIGKILL 信号不同,它可以被进程监听或忽略。这允许进程很好地关闭,通过释放分配给它的资源,如数据库连接或文件句柄。这种关闭应用程序的方式称为优雅关闭。
参考: https://nodejs.org/api/process.html#process_signal_events