javascript 使用 node.js 启动另一个节点应用程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18862214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Start another node application using node.js?
提问by Hydrothermal
I have two separate node applications. I'd like one of them to be able to start the other one at some point in the code. How would I go about doing this?
我有两个单独的节点应用程序。我希望其中一个能够在代码中的某个时刻启动另一个。我该怎么做呢?
回答by hexacyanide
Use child_process.fork()
. It is similar to spawn()
, but is used to create entire new instances of V8. Therefore it is specially used for running new instances of Node. If you are just executing a command, then use spawn()
or exec()
.
使用child_process.fork()
. 它类似于spawn()
,但用于创建 V8 的全新实例。因此它专门用于运行 Node.js 的新实例。如果您只是执行命令,请使用spawn()
或exec()
。
var fork = require('child_process').fork;
var child = fork('./script');
Note that when using fork()
, by default, the stdio
streams are associated with the parent. This means all output and errors will be shown in the parent process. If you don't want the streams shared with the parent, you can define the stdio
property in the options:
请注意,在使用 时fork()
,默认情况下,stdio
流与父级相关联。这意味着所有输出和错误都将显示在父进程中。如果您不希望与父级共享流,则可以stdio
在选项中定义该属性:
var child = fork('./script', [], {
stdio: 'pipe'
});
Then you can handle the process separately from the master process' streams.
然后,您可以从主进程的流中单独处理该进程。
child.stdin.on('data', function(data) {
// output from the child process
});
Also do note that the process does not exit automatically. You must call process.exit()
from within the spawned Node process for it to exit.
另请注意,该过程不会自动退出。您必须process.exit()
从生成的 Node 进程中调用它才能退出。
回答by JustEngland
You can use the child_process module, it will allow to execute external processes.
您可以使用 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
http://docs.nodejitsu.com/articles/child-processes/how-to-spawn-a-child-process