What's the purpose of the process exit event in node js?
I'm having a look at the docs of node.js: process event exit.
Emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all exit listeners have finished running the process will exit. Therefore you must only perform synchronous operations in this handler. This is a good hook to perform checks on the module's state (like for unit tests). The callback takes one argument, the code the process is exiting with.
Basic usage looks like this:
process.on('exit', function(code) {
console.log('About to exit with code:', code);
});
Despite the info in docs I can't think of a real life example where I'd like to do some unit tests inside of the callback.
I'd like to make my app as robust as possible. What do you use the exit
event for?
I use this event in my app as a last ditch chance to save state to disk in my app and to put some hardware my app is controlling in a known and safe state before my app shuts down. It works as a backstop so that no matter what causes my app to die, I still get a chance to clean up some things.
So, when this event is triggered, I check if there is any unsaved state and, if so, I write it to disk using synchronous I/O (you can't successfully use async operations in this event). Then, I turn off some hardware that my app is controlling.
我不认为这意味着你应该从这个回调中运行一个单元测试,但是一个正在运行的单元测试可能会使用这个回调来检查退出是否按预期触发,或者告诉退出单元失败。
链接地址: http://www.djcxy.com/p/52696.html上一篇: 什么阻止node.js退出进程?
下一篇: 节点js中的进程退出事件的目的是什么?