我有两个独立的Node应用程序。我希望其中一个能在代码的某个时刻启动另一个应用程序。我应该如何做到这一点?
我有两个独立的Node应用程序。我希望其中一个能在代码的某个时刻启动另一个应用程序。我应该如何做到这一点?
使用child_process.fork()
。它类似于spawn()
,但用于创建全新的V8实例。因此,它专门用于运行Node的新实例。如果您只是要执行一个命令,则使用spawn()
或exec()
。
var fork = require('child_process').fork;
var child = fork('./script');
请注意,使用fork()
时,默认情况下,stdio
流与父进程关联。这意味着所有输出和错误都将显示在父进程中。如果您不希望与父进程共享这些流,请在选项中定义stdio
属性:
var child = fork('./script', [], {
stdio: 'pipe'
});
那么您可以将该过程与主进程的流分开处理。
child.stdin.on('data', function(data) {
// output from the child process
});
请注意,此过程不会自动退出。您必须在生成的Node进程内调用process.exit()
以使其退出。
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
fork('./script, ['arg1','arg2']);
如果你想在子进程启动后传递变量,请使用child.send()
并在子进程中使用process.on('message', function(message) {});
进行监听。 - hexacyanide