使用node.js启动另一个节点应用程序? [英] Start another node application using node.js?

查看:798
本文介绍了使用node.js启动另一个节点应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

使用 child_process.fork() 。它类似于 spawn(),但用于创建V8的全新实例。因此它专门用于运行Node的新实例。如果您只是执行命令,则使用 spawn() exec()

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().

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

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

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:

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
});

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

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.

这篇关于使用node.js启动另一个节点应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆