简体   繁体   English

Node.js:停止执行除单个功能以外的所有代码吗?

[英]Node.js: stop execution of all code except a single function?

Is it possible to stop execution of all Node.js code, except for a single async function? 除了单个异步功能外,是否可以停止执行所有Node.js代码?

Kind of like running process.exit() , but process.exit() allows only sync functions. 有点像运行process.exit() ,但是process.exit()仅允许同步功能。

Ie a way to exit the current call stack, clear the message queue, unregister all event handlers, and then run a single async function? 即一种退出当前调用堆栈,清除消息队列,注销所有事件处理程序,然后运行单个异步功能的方法?

This is an interested use case... one thing you could do is fork a detached child_process that handles the async clean up for you. 这是一个有趣的用例...您可以做的一件事是派生一个独立的child_process,为您处理异步清理。 This way, you can send a message to the child prompting it to perform any cleanup prior to triggering a process.exit() on the parent to stop its process. 这样,您可以向子级发送一条消息,提示其执行任何清除操作,然后在父级上触发process.exit()以停止其进程。 The child should exit naturally through an emptying of its own event loop, but I put another process.exit() in the cleanup code just in case: 子级应该通过清空其自己的事件循环自然退出,但为防万一,我在清理代码中添加了另一个process.exit()

app.js app.js

const { fork } = require('child_process');
const subProcess = fork(`${__dirname}/cleanup.js`, {
  detached: true
});

//ensure parent can exit independent of child
subProcess.unref();

setTimeout(() => {
  //do some standard node.js, async stuff
  //all done... send clean up message and exit parent
  subProcess.send({ exit: true });
  //disconnect to sever any further communication
  subProcess.disconnect()
  process.exit(1);
}, 5000)

cleanup.js cleanup.js

asyncCleanUp();

async function asyncCleanUp(){
  setTimeout(() => {
    console.log('async cleanup completed... exiting.')
  }, 5000)
  return 'done'
}

console.log('cleanup script forked');
process.on('message', async (message) => {
  console.log(message)
  if(message.exit) {
    const result = await asyncCleanUp();
    console.log(result);
    process.exit(1);
  }
});

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

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