我的 Node 进程即将终止,当进程退出时我似乎无法登录到文件。这是一个长时间运行的进程,直接使用 node index.js
调用:
// index.js
const fs = require('fs');
exports.getAllCars = (process => {
if (require.main === module) {
console.log(`Running process: ${process.getgid()}.`);
let out = fs.createWriteStream(`${__dirname}/process.log`);
// trying to handle process events here:
process.on('exit', code => out.write(`Exit: ${code}`));
return require('./lib/cars').getAllCars();
} else {
return require('./lib/cars').getAllCars;
}
})(process);
还尝试为 error
、uncaughtException
创建事件处理程序。手动终止我的进程(使用 kill {pid}
)时没有任何效果。文件 process.log
已创建,但什么也没有。可写流是否需要在完成时调用stream.end()
?
最佳答案
根据 Node.js 文档:
The 'exit' event is emitted when the Node.js process is about to exit as a result of either:
- The
process.exit()
method being called explicitly.- The Node.js event loop no longer having any additional work to perform.
因此,如果您启动一个不应结束的进程,它就永远不会触发。
此外,可写流不需要关闭:
If
autoClose
(an option fromcreateWriteStream
) is set totrue
(default behavior) on error or end the file descriptor will be closed automatically.
但是,createWriteStream
函数默认打开带有'w'
标志的文件,这意味着每次都会覆盖该文件(也许这就是为什么你总是看到它是空的)。我建议使用
fs.appendFileSync(file, data)
以下是要监听的事件:
//catches ctrl+c event
//NOTE:
//If SIGINT has a listener installed, its default behavior will be removed (Node.js will no longer exit).
process.on('SIGINT', () => {
fs.appendFileSync(`${__dirname}/process.log`, `Received SIGINT\n`);
process.exit()
});
//emitted when an uncaught JavaScript exception bubbles
process.on('uncaughtException', (err) => {
fs.appendFileSync(`${__dirname}/process.log`, `Caught exception: ${err}\n`);
});
//emitted whenever a Promise is rejected and no error handler is attached to it
process.on('unhandledRejection', (reason, p) => {
fs.appendFileSync(`${__dirname}/process.log`, `Unhandled Rejection at: ${p}, reason: ${reason}\n`);
});
关于node.js - 如何记录 Node.js 进程错误事件的堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46330022/