有没有等效的asynchronous库,但对于node.js的child_processes

在节点中stream行的asynchronous库在处理asynchronous函数的复杂控制结构方面做了很多工作。 例如,假设我有一个银行帐户ID的集合,我想从一个API中检索余额,然后对余额进行求和。 我可以通过做这样的事情来实现asynchronous:

var accountIds = [0001,0002,0003,0004,0005,0006] async.mapLimit(accountIds, 3, function fetchBalance(accountID, cbk) { var balanceURL = "http://someapi.com/account/balance/" + accountID; get(balanceURL, cbk); }, function end(err, balances) { if (err) { console.err(err); } console.log(sum(balances)); } ); 

这使我不必编写pipe道,以跟踪同时分派多less个asynchronous函数,确保所有函数最终完成,跟踪错误等。另外,它在节点中工作良好,因为I / O(以networking请求)是这个程序的限制因素。

但是,让我们设想一下,不是有单独的任务是I / O绑定的,我们有单独的CPU绑定任务。 asynchronous不会给我任何真正的性能好处,因为node.js只会运行一个主线程。 在节点中并行处理这种工作负载的一种解决scheme可能是使用child_process库并生成一堆工作进程来处理CPU绑定的工作。 我的问题是,是否有一个库可以处理这些工作stream的pipe道/协调,如asynchronous为I / O绑定,asynchronousfunction? 如果没有,这是否值得写? 我认为这可能是一个有趣的练习。

我认为应该可以使用asynchronous与child_process一起实现你想要的。

 async.mapLimit(accountIds, 3, function(accountId, next) { child_process.execFile('myworker.js', [accountId], next); }, function(err, results) { console.log('done', err, results); }); 

我猜spawn / fork也可以使用,但是你必须监听事件,而不是callback来检查过程是否完成。

显然myworker.js应该做一些繁重的计算,否则最终会比在主线程中做得慢。 来自nodejs 文档 These child Nodes are still whole new instances of V8. Assume at least 30ms startup and 10mb memory for each new Node. That is, you cannot create many thousands of them. These child Nodes are still whole new instances of V8. Assume at least 30ms startup and 10mb memory for each new Node. That is, you cannot create many thousands of them.

如果要频繁使用这些进程,创build一次并向其发送消息来完成这项工作可能会更好,以避免启动成本。

对于特定情况,可能会为Node构build一个audio转换库。 否则,可以使用lame命令转换audio,但这意味着与shell命令交互的复杂性。

一般来说,build立一个暴露类似REST的URL的Express服务器是很容易的。

app.get('/path/:param', function(req, res, next) { CPUintensiveCalc(req.params.param, function(err, result) { res.send({ result: result}); }); });

然后在另一个Node.js应用程序中,可以使用http.request来调用服务。

我在这里写了一个更长的回复: http : //davidherron.com/blog/2014-07-03/easily-offload-your-cpu-intensive-nodejs-code-simple-express-based-rest-server