使用node.js启动另一个节点应用程序?

我有两个单独的节点应用程序。 我希望其中一个能够在代码中的某个时刻启动另一个。 我怎么去做这个?

使用child_process.fork() 。 它与spawn()类似,但用于创buildV8的全部新实例。 因此它专门用于运行Node的新实例。 如果你只是执行一个命令,然后使用spawn()exec()

 var fork = require('child_process').fork; var child = fork('./script'); 

请注意,使用fork() ,默认情况下, stdiostream与父级关联。 这意味着所有的输出和错误将显示在父进程中。 如果您不希望将stream与父级共享,则可以在选项中定义stdio属性:

 var child = fork('./script', [], { stdio: 'pipe' }); 

然后,您可以与主进程stream分开处理该进程。

 child.stdin.on('data', function(data) { // output from the child process }); 

另外请注意,该过程不会自动退出。 您必须从生成的Node进程中调用process.exit()以退出。

你可以使用child_process模块​​,它将允许执行外部进程。

 var childProcess = require('child_process'), ls; ls = childProcess.exec('ls -l', function (error, stdout, stderr) { if (error) { console.log(error.stack); console.log('Error code: '+error.code); console.log('Signal received: '+error.signal); } console.log('Child Process STDOUT: '+stdout); console.log('Child Process STDERR: '+stderr); }); ls.on('exit', function (code) { console.log('Child process exited with exit code '+code); }); 

http://docs.nodejitsu.com/articles/child-processes/how-to-spawn-a-child-process