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](https://fooobar.com/undefined)
source share