Greg Nisbet
Greg Nisbet

Reputation: 6994

Node.js create "weak callback" that doesn't prevent process from exiting

Is it possible to create a "weak callback" (by analogy with "weak reference") that doesn't prevent node.js from exiting? I'd like to be able to define an "optional handler" for a long-running asynchronous task that will get executed if the node.js process is still running, but doesn't prevent the event queue from being considered "empty" by itself. I don't have a real world use case for such a construction, I'm just wondering if node.js supports it (it might require a native extension).

Here's a really simple program that calls /bin/sh -c "sleep 9 ; ls" and waits for it to finish. The node.js process is basically idle for 9 second until the child process finishes.

var child_process = require("child_process");

child_process.exec("sleep 9 ; ls", function (err, stdout, stderr) {
    console.log(stdout);
});
console.log("end");

I'd like to be able to write something like this, where I'm using setTimeout to create a non-weak callback so the program is guaranteed to stay alive for at least three seconds. (Note: child_process.exec does have a timeout option, but that has to be set in advance, whereas this approach allows the deadline to be changed after the fact)

var child_process = require("child_process");

child_process.exec_weakly("sleep 9 ; ls", function (err, stdout, stderr) {
    console.log(stdout);
});
setTimeout(function() {}, 3000); // prevent exit for at least three seconds

console.log("end");

Upvotes: 3

Views: 271

Answers (1)

Byte
Byte

Reputation: 687

In case of timers you can use unref function like this:

 let timer = setTimeout(() => {
   console.log('tick');
 }, 3000);
 timer.unref();

Looks like you can do the same for child_process.spawn.

Upvotes: 3

Related Questions