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

Start another node application using node.js?

本文关键字:节点 应用程序 另一个 启动 node js 使用      更新时间:2023-09-26

我有两个独立的节点应用程序。我希望其中一个能够在代码中的某个点启动另一个。我将如何做到这一点?

使用 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()才能退出。

您可以使用

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