Wednesday, 15 March 2017

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.

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");



via Gregory Nisbet

No comments:

Post a Comment