How to run multiple node.js scripts from main node.js scripts?

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

+6
source share
2 answers

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

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

setTimeout and setInterval in the code are used only to show that both of them work simultaneously. The first module, when called, starts writing something to the console every 2 seconds, and the other module first waits for one second, and then starts doing the same every 2 seconds.

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

In the end, to run these two modules from the main Node.js script, which is called index.js here, you can easily execute:

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

and execute it as:

 node ./index.js 

Then you will have an output like:

enter image description here

+5
source

You can use child_process.spawn to run each of the node.js scripts in one. Alternatively, child_process.fork can satisfy your needs.

Baby process documentation

+1
source

Source: https://habr.com/ru/post/979897/


All Articles