Dave Dave - 2 months ago 10x
Node.js Question

Node.js - Require same module in Child process

I'm having a problem providing the same modules, or objects to my Child process.
Since there is no way to send a normal object to my Child process (I can only send the "server", a socket, or a JSON object), I tried to create a module, that I require in my main app.js, set any necessary data on it, and than in my child process, I would require it as well.

The problem is, that in my Child process, I get a different oject, not the one, I created in my app.js. I tried using a plain object, and setting a property on it, as well as a function...

//module file
var Data = function(){
this.data = null;

return this;

module.exports = Data;

...that I used like this...

var module = require("moduleName")();
module.data = "something";

...however in my Child process, data is still null

//Child process
var module = require("moduleName")();
console.log(module.data); --> null

Both files (app.js and the Child process's file) are in the same project, and directory.

My only gues is, because I created my Child process with
, it might using a different cache for modules...

So is there any way I can achieve, getting the same object in my Child process, or is there a way to send an object (not JSON) to my Child process?

Thanks in advance!

rsp rsp

The child process and the parent process are different processes - they don't share memory.

You would either have to use some inter process communication between them to synchronize the data, or use a common service like Redis that all of the process would use.

The way you are currently trying to do it is not possible, not just in Node. Any two processes will have their own memory and everything they send between themselves will not be shared or synchronized by itself.

Without using a service like Redis, you might communicate with your processes by sending messages.

When child is a reference to your child process in you parent process, then you can send messages with:


In your child you can listen for those messages with:

process.on('message', function(object) {
    // do something with object
    // like update your local copy

That way the parent process could notify all its child processes every time the object changes, sending them a fresh copy.

More info: