i
Creating a Web Server
Handling Get Requests
Handling Post Requests
Event Handling
Event Loop
Routing
Streams
Debugging a Node application
Framework in Node.js
Express.js
Templating Engine
Invoking a REST Service
Pre-requisites for Node.js
Introduction to Node.js
What to use Node.js for?
Node.js - Environment Setup
REPL Terminal
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.
Spawn
Exec
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:
Fork Spawns a new child process and all the child process share the same port.
syntax : cluster.fork([env])
Cluster module events
Fork
This event it emitted when a new worker thread is forked.
Online
Emitted when the worker is running
Listening
Emitted when calling listen() from a worker
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.
Don't miss out!