gpt4 book ai didi

Node.JS:在进程退出时执行多个回调

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:01 25 4
gpt4 key购买 nike

我在两个不同的组件中有两个不同的 Nodejs 服务器,但它们一起在同一个软件中运行。当我关闭程序时,我希望两台服务器都能正常退出,并释放各自的 TCP 端口。

对于他们每个人,我都有:

server1.js:

process.on('exit', function(){
server.close();
});

server2.js:

process.on('exit', function(){
server.close();
});

问题是,这两个函数中只有一个可以使用此方法运行。

将它们关闭在一个函数中不是一种选择。

是否有添加函数到“退出”事件?

最佳答案

Node.js 进程 exit 事件可以有多个监听器。

这个

process
.on('exit', () => console.log('foo'))
.on('exit', () => console.log('bar'));

应该导致

foo

bar

输出。

没有必要显式关闭 Node.js Web 服务器,因为它们会在进程退出时以任何方式关闭。

exit 事件监听器通常不适合关闭连接,因为这通常是异步过程。 exit 监听器应该是同步的:

Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned.

虽然 beforeExit 事件监听器在某些情况下可能会被跳过,但适合异步操作:

The 'beforeExit' event is emitted when Node.js empties its event loop and has no additional work to schedule. Normally, the Node.js process will exit when there is no work scheduled, but a listener registered on the 'beforeExit' event can make asynchronous calls, and thereby cause the Node.js process to continue.

<...>

The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling process.exit() or uncaught exceptions.

关于Node.JS:在进程退出时执行多个回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52679400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com