node.js - 如何记录 Node.js 进程错误事件的堆栈跟踪

标签 node.js error-handling

我的 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);

还尝试为 erroruncaughtException 创建事件处理程序。手动终止我的进程(使用 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 from createWriteStream) is set to true (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/

相关文章:

node.js - Socket.IO:使用大幅波动的数据更新客户端的最有效方法

javascript - 如何用json解决无效值的问题

node.js - 使用 Azure DevOps 部署 Node.js 应用程序会导致出现有关缺少模块的错误

php - 如何从 URL 中删除特定的 $_GET 变量

c++ - C++输入重定向在文件参数工作时导致错误

node.js - 无法在适用于 Linux 的 Windows 子系统(ubuntu)上运行 react 服务器

node.js - 无法运行 npm install -g expo-cli

go - Golang处理错误返回时删除重复的代码

Golang : Kill an os. 进程与 exec.ExitError

visual-studio-2010 - PostBuildEvent 多脚本错误处理