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

查看:157
本文介绍了在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天全站免登陆