我怎样才能从一个主要的node.js脚本运行多个node.js脚本?

我对node.js完全陌生。我有两个我想运行的node.js脚本。 我知道我可以单独运行它们,但我想创build一个运行这两个脚本的node.js脚本。主节点的代码应该是什么?

您只需要使用node.js模块格式,并为每个node.js脚本导出模块定义,如:

 //module1.js var colors = require('colors'); function module1() { console.log('module1 started doing its job!'.red); setInterval(function () { console.log(('module1 timer:' + new Date().getTime()).red); }, 2000); } module.exports = module1; 

 //module2.js var colors = require('colors'); function module2() { console.log('module2 started doing its job!'.blue); setTimeout(function () { setInterval(function () { console.log(('module2 timer:' + new Date().getTime()).blue); }, 2000); }, 1000); } module.exports = module2; 

正在使用代码中的setTimeoutsetInterval只是为了向您展示两者同时工作。 第一个模块被调用后,每2秒开始在控制台中logging一些内容,另一个模块首先等待一秒,然后每2秒开始一次。

我也使用了npm颜色包来允许每个模块以其特定的颜色打印输出(为了能够在命令中首先运行npm install colors )。 在这个例子中, module1打印red日志, module2打印blue日志。 所有这些只是为了向您展示如何在JavaScript和Node.js轻松实现并发。

最后,从一个名为index.js的主Node.js脚本运行这两个模块,您可以轻松完成:

 //index.js var module1 = require('./module1'), module2 = require('./module2'); module1(); module2(); 

并像这样执行它:

 node ./index.js 

那么你会有一个输出:

在这里输入图像描述

你可以使用child_process.spawn来启动每一个node.js脚本。 或者, child_process.fork也可能适合您的需要。

subprocess文档