我的节点工艺已行将就木,我似乎无法登录到一个文件时,程序退出。它是直接与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的文件:
当Node.js的过程将要退出作为的任一结果的“退出”事件被发射:
- 该
process.exit()
方法的显式调用。- Node.js的事件循环不再有任何额外的工作来进行。
所以,如果你启动一个过程,应该永远不会结束,它永远不会触发。
此外,可写流并不需要被关闭:
如果
autoClose
(从createWriteStream
选项)设置为true
(默认行为)上的错误或结束文件描述符将被自动关闭。
然而,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`);
});
我建议你把代码放在一个try catch块以确定是否其代码或导致程序终止某些外部原因。然后检查日志在事件发生后...
try {
//your code
}catch(e) {
console.log(e.stack);
}