The child_process module will somewhat do what you want.
Only issue is, you literally spawn new processes, so hence, there is a memory overhead that you have to consider. Assuming you want the elegance of defining your subroutines within the same file, you can pass a JavaScript string to the node command.
So this is exactly what we will do. But first, let's create a function that accepts a JSON-compatible object, and a function, which will then run that function on a new thread:
var child_process = require('child_process');
function startThread(data, fn, callback) {
var fnStr = '(' + fn.toString() + ')(' + JSON.stringify(data) + ');';
var node = child_process.spawn('node', ['-e', fnStr]);
var output = [];
var onData = function (data) {
output.push(data.toString('utf8').trim());
};
node.stdout.on('data', onData);
node.stderr.on('data', onData);
node.on('close', function (code) {
callback(code, output);
});
}
And as an example, we are going to be spawning a new thread to generate the lyrics of the "99 bottles of beer" song:
startThread({ doFor: '99' }, function (data) {
var str = '';
while (data.doFor) {
str += data.doFor + ' bottles of beer on the wall ' + data.doFor +
' bottles of beer. You take one out, toss it around, ';
data.doFor--;
str += data.doFor + ' bottles of beer on the wall\n';
}
console.log(str.trim());
}, function (code, outputs) {
console.log(outputs.join(''));
});
Unfortunately, the function that will be used in the other "thread" wouldn't have access to variables in the parent thread.
And also, data is passed through STDOUT and STDERR.