Open In App

NodeJS Program Lifecycle

Improve
Improve
Like Article
Like
Save
Share
Report

Node.js is a JavaScript runtime that is built on Chrome’s V8 JavaScript engine and its run-time environment includes everything which we need to execute a program written in JavaScript. It uses an event-driven, non-blocking I/O model that makes it most scalable and popular. Non-blocking simply means multiple requests can be processed in parallel.

Lifecycle of Node.js program: In order to understand its lifecycle you must be familiar with the event loop. Event loops are something that makes your task very fast and also it perform multitasking. It allows Node.js to perform non-blocking I/O operations. You can learn more about event loop here. When you run your node file using node app.js then the script starts executing. It will be parsed by the parser into machine language that simply means all the functions and variables get registered in a memory location. After parsing the code our program reaches the point where it will not exit and will run an infinite no. of times which is possible all because of the event loop. Once the event loop has started executing and it will run as long as event listeners are registered.

Example: You have the database and you have to access data from the database or you want to insert something into a database that simply requires some calling of the functions so when you call them it will take some amount of time (maybe nanoseconds or microseconds but it will take some time) so it is not possible for every request that we can wait for that particular time and then we move on to next request so that is where event loop comes into the picture. Your database part will be run in the background and the event loop will be running continuously so that it can handle the need for another request as well. This will be done on a single thread in node.js. You can also come out of the loop explicitly by using process.exit().

Javascript




const http = require('http');
const server = http.createServer(function (req, res) {
  
console.log("server is running");
process.exit();
  
});
  
server.listen(8000);


Explanation: In the above program inside createServer() method, you have written simply process..exit() so as soon as you will run this program using node app your server will wait for listening to your request and once you will provide it with the request it will exit from the event loop. By calling this function, Node.js will force the current process which is currently running to abort as soon as possible and if there are any asynchronous operations taking place, they will also be terminated immediately.

Timers: The timer modules in Node.js consists of functions that help to control the timings of code execution. It includes setTimeout(), setImmediate(), and setInterval() methods.

  • setTimeout() Method: The setTimeout() method is used to schedule code execution after a designated amount of milliseconds. The specified function will be executed once. We can use the clearTimeout() method to prevent the function from running. The setTimeout() method returns the ID that can be used in clearTimeout() method.

    Javascript




    let str = 'GeeksforGeeks!'
      
    setTimeout(function () { 
        return console.log(str); 
    }, 5000); 
      
    // This console log is executed right away 
    console.log('Executing setTimeout() method'); 

    
    

  • setImmediate() Method: The setImmediate() method is used to execute code at the end of the current event loop cycle. Any function passed as the setImmediate() argument is a callback that can be executed in the next iteration of the event loop.

    Javascript




    let str = 'GeeksforGeeks!'
      
    setImmediate(function () { 
        return console.log(str); 
    }); 
      
    // This console log is executed right away 
    console.log('Executing setImmediate() method'); 

    
    

  • setInterval() Method: The setInterval() method is used to call a function at specified intervals (in milliseconds). It is used to execute the function only once after a specified period.
    We can use the clearInterval() method to prevent the function from running. The setInterval() method returns the ID which can be used in clearInterval() method.

    Javascript




    let str = 'GeeksforGeeks!'
      
    setInterval(function() { 
        return console.log(str); 
    }, 5000); 
      
      
    // This console log is executed right away 
    console.log('Executing setInterval() method'); 

    
    

Learn more about timers in Node.js here.

process.nextTick(callback) Method:Whenever a new queue of operations is initialized we can think of it as a new tick. The process.nextTick() method adds the callback function to the start of the next event queue. It is to be noted that, at the start of the program process.nextTick() method is called for the first time before the event loop is processed.

timers–>pending callbacks–>idle,prepare–>connections(poll,data,etc)–>check–>close callbacks



Last Updated : 19 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads