如何从一个主要的node.js脚本运行多个node.js脚本? [英] How can I run multiple node.js scripts from a main node.js scripts?

查看:217
本文介绍了如何从一个主要的node.js脚本运行多个node.js脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对node.js完全陌生.我有两个要运行的node.js脚本.我知道我可以分别运行它们,但是我想创建一个同时运行两个脚本的node.js脚本.主要的node.js脚本的代码应该是什么?

I am totally new to node.js .I have two node.js script that I want to run . I know I can run them separately but I want to create a node.js script that runs both the scripts .What should be the code of the main node.js script?

推荐答案

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

All you need to do is to use the node.js module format, and export the module definition for each of your node.js scripts, like:

//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秒开始在控制台中记录一些内容,另一个模块首先等待一秒钟,然后每2秒开始执行相同的操作.

The setTimeout and setInterval in the code are being used just to show you that both are working concurrently. The first module once it gets called, starts logging something in the console every 2 second, and the other module first waits for one second and then starts doing the same every 2 second.

我还使用了 npm颜色包,以允许每个模块以特定颜色打印其输出(要执行此操作,请先在命令中运行npm install colors).在此示例中,module1打印red日志,而module2打印其日志在blue中.所有这些只是向您展示了如何轻松地在JavaScript和Node.js中进行并发.

I have also used npm colors package to allow each module print its outputs with its specific color(to be able to do it first run npm install colors in the command). In this example module1 prints red logs and module2 prints its logs in blue. All just to show you that how you could easily have concurrency in JavaScript and Node.js.

最后,从一个主要的Node.js脚本(在这里命名为index.js)运行这两个模块,您可以轻松地做到这一点:

At the end to run these two modules from a main Node.js script, which here is named index.js, you could easily do:

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

module1();
module2();

并像这样执行它:

node ./index.js

然后您将得到类似以下的输出:

Then you would have an output like:

这篇关于如何从一个主要的node.js脚本运行多个node.js脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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