简体   繁体   中英

How do I make NodeJS terminate even if I have “non-essential” things in the EventQueue?

I don't have good terms for everything, so please be patient.

In a NodeJS script, execution will complete once the event queue is cleared out. In my package, however, I want to add a non-essential long-running thing to the event queue (eg spawned process or setInterval call) and automatically trigger cleanup of that non-essential task once the script would naturally finish had I not added the long-running thing.

Since I'm producing a package, I could make the user of the package call a close() method (and make them responsible for keeping track of when everything else is done. But I'd rather automatically close so the user doesn't have to worry about it.

I'll use setInterval as an example, but I'd really like for this to work with a spawned subprocess. I'm hoping for something like this:

function main() {
  let myinterval = setInterval_NonEssential(() => {
    console.log("Still alive");
  }, 1000);
  process.on('only-non-essential-work-remains', () => {
    clearInterval(myinterval);
  });

  // do any number of other things
  // ...
}

main();

Is there a way to tag event queue things in such a way? Do you have a better suggestion for how to accomplish this?

setInterval returns a Timeout object which offers an unref method which tells node to ignore this handle regarding the question "is there still something going on".

Similar a lot other objects like net.Server or ChildProcess offer an unref method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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