I have an application where there is a portion that is computationally intensive. I would like to move that computation off to a background task and have it notify the main Node.js thread when it is complete. I see a number of possible solutions out there including Node Background Task, ClusterHub, Node Threads A-Go-Go, and I am sure there are others.
Does anyone have experience with this and can recommend a solution?
Thanks, John
Processes are simple enough that it's not worth the trouble to wrap them with an library or npm module unless you need special functionality, such as automatic respawning of background daemons. The built-in Node API 'child_process' handles processes, and using it is simple:
var childProcess = require("child_process");
var child = childProcess.spawn("/usr/bin/uname", ["-a"]);
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
var stdoutBuffer = "", stderrBuffer = "";
child.stdout.on("data", function(data){stdoutBuffer += data;});
child.stderr.on("data", function(data){stderrBuffer += data;});
child.on("close", function(code)
{
//the process exited with code `code`
console.log("Stdout:", stdoutBuffer);
process.exit(code); //bubble up the exit code
});
If you need order-independent asynchronous control flow, consider using promises (I recommend the npm module 'q' by kriskowal.) Creating a promise when your task starts, and resolving/rejecting it upon completion (in the "close" event handler) would make for a clean and predictable way to perform follow-up tasks after your background job is done.