Search code examples
javascriptnode.jsmoduleinstancenode-modules

NodeJS - One instance of class/module in 2 processes


I have a class in a file that exports it, as following:

myClass.js:

class testClass {
  key = 'initial value';
  constructor(){
    return this;
  }
}

module.exports = testClass;

Then I have 2 node files that run separately:

let instance = new require("./myClass.js");
instance.key = 'changed value';
// Keeps running

and

let instance = new require("./myClass.js");
console.log(instance.key);
// Also keeps running

Question

How can I make the second process print "changed value" instead of "initial value"?

Notes:

  • I tried running the 2nd file after the 1st one;
  • This is a very simplified example of what I need, I changed the context to make it more understandable.

Solution

  • Difficult, I think that you can not share the seme object in memory between 2 process.

    Maybe you have to think about create a third process that contains the data.

    For example: dnode https://github.com/substack/dnode

    or use some fast memory db as Redis


    Process 0: data store, dnode or Redis

    Process 1: connect to data store and set a new value

    Process 2: connect to data store and get the value