Cluster Worker Object in Node.js


This article explains what Worker Objects are. A Worker object does not inherit from any class or interface. You can have more than one worker running at once with its own thread.

Worker Object

A Worker Object is a script that runs in a background process and does not block the other code processes attached to the page. A Worker Object contains all the public information and methods about a worker. The master can use "cluster.workers." If a worker throws an exception and does not handle the exception itself, the exception will create an event that you can listen for as an onerror event.
A unique id is provided to each worker. This unique id is resides in the "id". While a worker is alive, on the basis of the unique id we can get the indexes from the cluster.workers.
Workers are created using "child_process.fork()", the returned object from this function is stored as ".process". Child nodes are entire new instances of V8. Allow at least 30ms startup and 10mb for each new node. A ChildProcess class is not intended to be used directly; use the "spawn()" or "fork()" methods to create child process instances.
Methods of Worker Class
  • Worker.send(message,[sendHandle])
  • Worker.kill() : This function kills the workers.
  • Worker.Disconnect()
The Send function contains two arguments, the first one is a message object and the other one is a Handle object. This function is equal to the send method provided by "child_process.Fork()". In the master you should use this function to send a message to a specific worker. In the worker you can also use "process.send(message)".
The Disconnect function closes all the servers. Wait for the close event on those servers and then disconnect the IPC channel. In the master, an internal message sent to the worker causes it to call disconnect itself.
Now use the following procedure to persist the data in a cluster Worker Object.
Step 1
Open any editor. I am using Notepad. Write the following code and save the file with a .js extension as in the following figure:
In the example above you need to map and re-map " data" on every fork and exit event.
Step 2
Now open the node.js environment. If you don't have node.js then you can install it using this link get Node.js as in the following figure :
Step 3
Now provide the specified path of where you saved the .js file as in the following figure:


This article has taught you about the Worker Object and you saw how a cluster worker persists the data in node.js. Workers have limited scope; they cannot access most of the web pages but do have access to the global core of JavaScript objects.