2

I am running a node js application. When it starts I create one worker per core. I need to create some kind of global variable shared between every worker I created. Is there any way to do this?

0

2 Answers 2

6

For a small set of variables you can spawn workers with custom environments. For example:

// On the master when creating the process:
cluster.fork({ GLOBAL_VAR_A: 12345 });

// On workers:
var globalA = parseInt(process.env.NODE_GLOBAL_VAR_A, 10);

I've put a parseInt in here to highlight that environment variables are strings. This should only be used for a few variables though, since it obviously scales badly.

There are two important alternatives though

  • Configuration Files: Much of the time, data you want to share is really configuration. Configuration can be simply stored in files, and all workers will read in the same data.
  • Databases: The other is shared state via database. For example, redis pubsub allows you to maintain synchronised variables between workers, if you really need it.

As mentioned in alex's answer, native cluster IPC is an option too, but is really for communicating between master and workers. You don't want to have your master process doing too much to avoid possible bugs that throw uncaught exceptions. It may also be worth looking at zeromq etc.

Sign up to request clarification or add additional context in comments.

Comments

2

No, there is no way to do that.

Node.js workers are intentionally independent from each other, and only way for them to communicate is to send serialized objects over some channel (TCP/Pipe/IPC/etc.).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.