在 Node.js 退出之前执行清理操作 [英] Doing a cleanup action just before Node.js exits

查看:50
本文介绍了在 Node.js 退出之前执行清理操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想告诉 Node.js 总是在它退出之前做一些事情,无论出于什么原因 - Ctrl+C、异常或任何其他原因.

I want to tell Node.js to always do something just before it exits, for whatever reason — Ctrl+C, an exception, or any other reason.

我试过了:

process.on('exit', function (){
    console.log('Goodbye!');
});

我启动了这个进程,杀死了它,什么也没发生.我再次启动它,按下Ctrl+C,仍然没有任何反应......

I started the process, killed it, and nothing happened. I started it again, pressed Ctrl+C, and still nothing happened...

推荐答案

更新:

您可以为 process.on('exit') 注册一个处理程序,并在任何其他情况下(SIGINT 或未处理的异常)调用 process.exit()

UPDATE:

You can register a handler for process.on('exit') and in any other case(SIGINT or unhandled exception) to call process.exit()

process.stdin.resume();//so the program will not close instantly

function exitHandler(options, exitCode) {
    if (options.cleanup) console.log('clean');
    if (exitCode || exitCode === 0) console.log(exitCode);
    if (options.exit) process.exit();
}

//do something when app is closing
process.on('exit', exitHandler.bind(null,{cleanup:true}));

//catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {exit:true}));

// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', exitHandler.bind(null, {exit:true}));
process.on('SIGUSR2', exitHandler.bind(null, {exit:true}));

//catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {exit:true}));

这篇关于在 Node.js 退出之前执行清理操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆