我完全不了解node.js。我有两个node.js脚本需要运行。我知道可以分别运行它们,但我想创建一个运行这两个脚本的node.js脚本。主node.js脚本的代码应该是什么?
我完全不了解node.js。我有两个node.js脚本需要运行。我知道可以分别运行它们,但我想创建一个运行这两个脚本的node.js脚本。主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秒后开始以相同的频率记录。
我还使用了npm colors package,以便让每个模块的输出带有其特定的颜色(要先在命令中运行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
然后你会得到这样的输出:
require()
将它们引入,并针对每个模块执行相应的主函数。 - jfriend00