How Can I Run Multiple Node.js Scripts From A Main Node.js Scripts?
Solution 1:
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.jsvar colors = require('colors');
functionmodule1() {
console.log('module1 started doing its job!'.red);
setInterval(function () {
console.log(('module1 timer:' + newDate().getTime()).red);
}, 2000);
}
module.exports = module1;
and
//module2.jsvar colors = require('colors');
functionmodule2() {
console.log('module2 started doing its job!'.blue);
setTimeout(function () {
setInterval(function () {
console.log(('module2 timer:' + newDate().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.jsvar module1 = require('./module1'),
module2 = require('./module2');
module1();
module2();
and execute it like:
node ./index.js
Then you would have an output like:

Solution 2:
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.
Post a Comment for "How Can I Run Multiple Node.js Scripts From A Main Node.js Scripts?"