Understanding the Node lifecycle and event loop in node.js


Simple http server in node.js will register an event loop which will keep on listening for http requests.

Execution of file containing code for creation of server will work as shown below −

node App.js => Start executing script => Code parsing, Register events and functions => event loop=> keeps on running as long as event are registered.

This is the single threaded event driven approach of the node.js. For accessing and updating of values in database also works using the event driven approach. Even though it’s a single threaded, it can handle multiple requests at a time due to its speed of handling.

Example −

const server = http.createServer( (req, res)=>{ console.log(‘hello’); } );

In above example code, createServer method takes request listener as an argument which an event . This event will keep on listening to an http requests on specified port.

How to exit from event loop

process.exit() is the function that will stop the event loop.

App.js

const http = require(‘http’);
const server = http.createServer( (req, res)=>{ console.log(‘hello’); process.exit(); } );
server.listen(3000);

Now, once we run the App.js file using node App.js using terminal, the event loop will start. The event loop will stop on receiving the first http request. This can be checked from opening a browser and navigate to localhost:3000, and se the console log in terminal. It will print hello message and also stops the event loop.

process.exit() is rarely used as we always to keep the event loop running to listen http requests or connection to database. It can be used based on specific requirements only.

If we just need to exit from terminal by stopping node process, we can use ctrl + c in terminal to stop the node process.

Event loop follows a non blocking code execution.

Simple Event Emitter example

// import the core module events from node.js
const events = require('events');
//create an object of EventEmitter class by using above reference
var em = new events.EventEmitter();
//Subscribe for FirstEvent
em.on('TutorialsPointEvent', function (data) {
   console.log(' Hello Tutorials point Event': ' + data);
});
// Raising FirstEvent
em.emit(' TutorialsPointEvent', 'This is my first Simple Node.js event emitter example on TutorialsPoint.');

Updated on: 13-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements