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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With