i

Scaling Node Application

Well, we have learnt a lot of concepts in Node.js by now. But we know, Node.js is single threaded, if we have multiple requests coming in and we need to handle it with multiprocessor; we should make Node application scalable.

Node has built-in modules like child_process and cluster for making our application scalable.         

Node.js is single threaded and it makes Node.js processes efficient and faster.

Most servers have multiple processors and we can take advantage of this for scaling Node.js application.

We can Fork worker processes from main application to separate child processes. These child processes can work in parallel to the other child processes and main application.

Child_process module

This built-in module is created to create child processes from the main process to leverage paraller processing on multi-core CPU bases systems.

There are multiple methods provided by child_process module.

  1. Spawn

  2. Exec

  3. Fork

1. Spawn :

This method launches a new child process and returns a child process object.

Syntex : spawn(command, [args], [options])

Spawn_child.js

Spawn_parent.js

Output :

Exec method

This method launches a new child process and runs the given command in a shell.

Syntex: exec(command,[options],callback)

Exec-demo.js

execFile-demo.js

Output

Fork method

It is modified form of spawn() method for creating child processes.

Syntex: Fork(modulepath,[args],[options])

Fork-child-demo.js

Fork-demo.js

Output

Cluster Module:

Cluster module is a built-in module and created on top of child_process.fork().

This moule has methods like:

  1. Fork Spawns a new child process and all the child process share the same port.

    syntax : cluster.fork([env])

Cluster module events

  1. Fork
    This event it emitted when a new worker thread is forked.

  2. Online
    Emitted when the worker is running

  3. Listening
    Emitted when calling listen() from a worker

  4. Exit
    Emitted when a worker is killed

Cluster-demo.js

Output

So, we have four worker threads created.

We can four different instances of applications running alongside.