最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I run multiple node.js scripts from a main node.js scripts? - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share Improve this question asked Dec 19, 2014 at 6:46 Sagar KariraSagar Karira 6792 gold badges8 silver badges20 bronze badges 1
  • 2 You can just make the two scripts be modules that each export one master function. You require() them in and execute that one master function on each. – jfriend00 Commented Dec 19, 2014 at 6:48
Add a comment  | 

2 Answers 2

Reset to default 12

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;

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. 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.

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.

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();

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. Alternatively, child_process.fork might suit your need too.

Child Process Documentation

发布评论

评论列表(0)

  1. 暂无评论