Given an index.js
script that defines an app within a variable (i.e. a collection of in-memory state and methods), how would you go about ensuring that calls to run the script operate on an existing instance of the app, and not just create new instances?
For example, consider this app that just defines a counter, and methods to start an increment interval, pause the interval, and read the current count:
// ####################################################
// Define app
// ####################################################
const app = (() => {
let counterInterval;
let counter = 0;
function startCounter() {
counterInterval = setInterval(() => counter++, 1000);
}
function pauseCounter() {
clearInterval(counterInterval);
}
function showCounter() {
console.log(counter);
}
return {
startCounter,
pauseCounter,
showCounter,
}
})();
// ####################################################
// Run selected app method
// ####################################################
const argvs = process.argv.slice(2);
const [command, ...args] = argvs;
if (command === 'startCounter') {
app.startCounter();
}
if (command === 'pauseCounter') {
app.pauseCounter();
}
if (command === 'showCounter') {
app.showCounter();
}
If I run node ./index.js startCounter
, the app runs and the terminal is locked into the process. How can I make it so that:
- The process runs in the background; and
- Subsequent calls to
node ./index.js showCounter
show the value of the counter within the app that was originally ran (as opposed to creating new processes)?
The requirement seems to me like quite a common use case, so I’m thinking that there must be a mechanism in NodeJS that provides for this, but I can’t find one. Do I have to use third party toolkits for this?