简体   繁体   English

如何从主node.js脚本运行多个node.js脚本?

[英]How can I run multiple node.js scripts from a main node.js scripts?

I am totally new to node.js .I have two node.js script that I want to run . 我对node.js完全不熟悉。我有两个我想运行的node.js脚本。 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: 您需要做的就是使用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;

and

//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;

The setTimeout and setInterval in the code are being used just to show you that both are working concurrently. 代码中的setTimeoutsetInterval仅用于向您显示两者同时工作。 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. 第一个模块一旦被调用,就会每隔2秒开始在控制台中记录一些内容,而另一个模块先等待一秒,然后每隔2秒开始执行相同的操作。

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). 我还使用了npm colors包来允许每个模块以其特定颜色打印其输出(能够在命令中首先运行npm install colors )。 In this example module1 prints red logs and module2 prints its logs in blue . 在此示例中, module1打印red日志, module2blue打印其日志。 All just to show you that how you could easily have concurrency in JavaScript and Node.js . 所有这些只是为了向您展示如何在JavaScript和Node.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的主Node.js脚本运行这两个模块,您可以轻松地执行以下操作:

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

module1();
module2();

and execute it like: 并执行它:

node ./index.js

Then you would have an output like: 然后你会得到一个输出:

在此输入图像描述

You can use child_process.spawn to start up each of node.js scripts in one. 您可以使用child_process.spawn在一个中启动每个node.js脚本。 Alternatively, child_process.fork might suit your need too. 或者, child_process.fork也可能适合您的需要。

Child Process Documentation 子进程文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM