简体   繁体   English

Node.JS 处理全局事件监听器

[英]Node.JS Process global event listeners

I was wondering if there is any way i could declare event listeners on the Node.JS' process module.我想知道是否有任何方法可以在 Node.JS 的process模块上声明事件侦听器。 ie being able to define event listeners in one file globally which applies to the entire project.即能够在一个全局文件中定义事件监听器,该文件适用于整个项目。

For example: I want to be able to listen to the process module's on(exit) event to perform some logging before the process quits with the mentioned or default exitCode (This is in a saperate file from where i'd call the process.exit()例如:我希望能够侦听进程模块的on(exit)事件以在进程使用提到的或默认的exitCode退出之前执行一些日志记录(这是在我调用process.exit()的单独文件中process.exit()

if(!process.env.TELEGRAM_TOKEN) {
   process.exit(100);
}   

and i have the listener in another module declared as:我在另一个模块中声明了监听器:

process.on("exit", (code) => {
switch(code) {
    case 100:
        console.error(`${code} - ${NO_API_KEYS}`);
        break;
    default:
        console.error(`${code} - ${DEFAULT_EXIT_ERROR}`)
}
});

Problem is - It exits with code 100 but it never logs the console.error() defined on the event listener.问题是 - 它以代码100退出,但它从不记录事件侦听器上定义的console.error()

It appears that your module is not being loaded so the code is never being run to register the event handlers for the exit event.看来您的模块没有被加载,所以代码永远不会被运行来注册exit事件的事件处理程序。

All you have to do to get its initialization code to run is to import the module from your main app module or any other module of yours that is part of your app initialization.要运行其初始化代码,您所要做的就是从您的主应用程序模块或属于您的应用程序初始化的任何其他模块导入该模块。

import './mymodule.js'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM