Node.js – 在不同进程中运行代码的最简单的方法

在不同的进程中运行一些代码并将结果与​​主进程交stream的最简单的方法是什么?

所以我有一个相当密集的任务,需要分解成不同的过程。 什么是最简单的方法来做这样的事情?

// in main process var otherProcess = createAnotherProcess(function() { console.log("this code is ran in another process"); return "some data"; }); otherProcess.on("done", function(data) { console.log(data); // will output "some data" }); 

拥有能够在多个进程中运行代码的单个源代码文件将非常棒! 这甚至有可能吗? 我试着在节点上读一些关于“child_processes”的内容,但是发现它太复杂了。

任何帮助?

 var spawn = require("child_process").spawn; var stat = spawn("dstat", ["-r", "--noheaders", "--nocolor"]); var output = function (output_data) { //do something with output_data }; stat.stdout.on("data", output); 

http://nodejs.org/docs/v0.4.11/api/child_processes.html

要在subprocess中运行一些命令,可以使用child_process.spawn方法。

如果你想运行一些沉重的JS代码,你可以把它分割成块来不使用process.nextTick来阻塞IO。

使用dimas-parallel (在npm上 ):

 var dimas = require('dimas-parallel); dimas.execute(function() { // do some stuff on another process });