【发布时间】:2015-02-18 02:09:05
【问题描述】:
我对 node.js 完全陌生。我有两个要运行的 node.js 脚本。我知道我可以单独运行它们,但我想创建一个运行这两个脚本的 node.js 脚本。主 node.js 脚本的代码应该是什么?
【问题讨论】:
-
你可以把这两个脚本做成模块,每个模块都导出一个主函数。你
require()他们并在每一个上执行一个主函数。
标签: javascript jquery node.js
我对 node.js 完全陌生。我有两个要运行的 node.js 脚本。我知道我可以单独运行它们,但我想创建一个运行这两个脚本的 node.js 脚本。主 node.js 脚本的代码应该是什么?
【问题讨论】:
require()他们并在每一个上执行一个主函数。
标签: javascript jquery 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;
代码中的setTimeout 和setInterval 仅用于向您展示两者同时工作。第一个模块一旦被调用,就会每 2 秒开始在控制台中记录一些内容,而另一个模块首先等待 1 秒,然后每 2 秒开始执行相同的操作。
我还使用了npm colors package 来允许每个模块使用其特定颜色打印其输出(以便能够首先在命令中运行npm install colors)。在此示例中,module1 打印 red 日志,module2 在 blue 中打印其日志。这一切只是为了向您展示如何在 JavaScript 和 Node.js 中轻松实现并发。
最后从主要的Node.js 脚本运行这两个模块,这里命名为index.js,您可以轻松做到:
//index.js
var module1 = require('./module1'),
module2 = require('./module2');
module1();
module2();
并像这样执行它:
node ./index.js
然后你会得到这样的输出:
【讨论】:
您可以使用child_process.spawn 来同时启动每个 node.js 脚本。或者,child_process.fork 也可能满足您的需求。
【讨论】: