Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How React JSX gets Transformed into JavaScript behind the Scenes
Next article icon

How Node.js works behind the scene ?

Last Updated : 29 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
Node.js is the JavaScript runtime environment which is based on Google’s V8 Engine i.e. with the help of Node.js we can run the JavaScript outside of the browser. Other things that you may or may not have read about Node.js is that it is single-threaded, based on event-driven architecture, and non-blocking based on the I/O model. 1) Node.js Architecture: Node.js is made of Chrome V8 engine which is written in C++ and Libuv which is a multi-platform C library that provides support for asynchronous I/O based events on event loops and thread loops. Don’t worry it is explained in this later at the end. An important thing that we need to remember is that, even though Node.js is made using the V8 engine and Libuv which are written in C or C++, we can still use Node.js in pure JavaScript. 2) Node.js Application: So now that, we have learned about the Node.js architecture, it’s time to learn how a Node.js application runs and this part includes the concept of Node.js being single-threaded and its non-blocking nature as well. So, first of all, what is a thread? A thread in simple terms is basically a set of programming instructions that can be run independently in a computer’s processor and every process that we want to run has its own thread to run the programming instructions and the process can have more than one thread. But, the point to remember is, Node.js application runs only on a single thread and by that, It mean whether that Node.js application is being used by 5 users or 5 million users, it will only run on a single thread which makes the Node.js application blockable (which means that a single line of code can block the whole app because an only single thread is being used). So, to keep the Node.js application running, asynchronous code must be used everywhere having callback functions because as we know that asynchronous code keeps on running in the background and the callback gets executed as soon as the promise gets resolved rather than synchronous code which blocks the whole application until it gets finished executing. But, we can still use synchronous code however at someplace in our application and that place is before our application enters Event-loop. Event-loop is what allows Node.js applications to run non-blocking asynchronous I/O based operations i.e, all the asynchronous code is managed and executed within the event-loop and before that, we can use our synchronous code which is in this case known as Top-Level code. So, try to write synchronous code only for those operations which are executed only once at the start of our application and not every time, for Ex: reading some data from your computer memory which later can be requested by some user (many times) in asynchronous code. The following figure is the chart visualizing:

So, as you can see whenever the Node.js application starts in a thread, the first step is to initialize the application and execute the top-level code which as we have said earlier is the only synchronous code that we should have in our application. The next step is to require the modules that we specified in our code (which is normally written at the very top).

The very next step is to register all the event callbacks which are in our code which will then be sent to the event-loop for execution where most of our code in node app is executed. But some times, some tasks are too heavy to be executed in our event-loop by a single thread so those tasks are sent to the thread-pool (provided by Libuv) are the 4 extra threads to execute heavier tasks without blocking the main thread. The number of threads can be increased and the user did not have to specify the tasks which have to be off-loaded because event-loop does it all by itself but we can specify the number of threads.

3) The Event-loop: So, you need to remember this point that event-loop is the place where all our asynchronous code is executed. For a moment, why don’t you in the first paragraph and read that again because we will be covering the third point of Node.js which is that, it is based on event-driven architecture. The whole idea behind the event-loop is that it works on this architecture or these three steps as shown below:

  1. Events are emitted, These events can emit from any asynchronous function like getting an HTTP request, fileSystem module finished reading the file or a timer has been finished. These events can vary on our code.
  2. After that, Event-loop picks them up.
  3. Callback functions are executed (based on your code).

Other than this, event-loop offloads heavier tasks to the thread-pool.

Note: Event-loop does follow a sequence to run the callbacks.

Typically, an event-loop has 4 phases and for each phase, it sets a callback queue that contains callback functions from the emitted event.

  1. The first phase is the Expired timeout callbacks, which are the callback functions from setTimeout() function etc.
  2. The second phase is the callbacks from I/O polling like an event of reading a file or any HTTP request.
  3. The third phase is the callbacks from the setImmediate() function, which are the callback functions that the user wants to execute just after the I/O polling. These type of functions can be specific for some only certain cases.
  4. And the last is, Close callbacks which are emitted from events like the closing of the webserver, etc.
Note: All the callbacks available from the certain phase are first executed and only then it goes to the next phase. Also, at the end of the event-loop, it checks whether any other event is still going on and if it is then it returns back to the first phase and so on otherwise the program exits from the event-loop.

Next Article
How React JSX gets Transformed into JavaScript behind the Scenes

S

sarthakduggal
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node.js-Misc

Similar Reads

  • Explain the working of Node.js
    Welcome to the world of Node.js, an open-source runtime environment that has transformed the landscape of backend development. Traditionally, JavaScript was confined for frontend development, powering user interactions on the browser. However, with the advent of Node.js, JavaScript has broken free f
    4 min read
  • How to work with Node.js and JSON file ?
    Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging d
    4 min read
  • How JavaScript works and code is executed behind the scene ?
    JavaScript is an interesting language in the world and its working procedure quite be different from other languages. JavaScript is synchronous(specific order of execution), single-threaded language(it means JavaScript can only execute one command at a time).  Everything in JavaScript happens inside
    3 min read
  • How React JSX gets Transformed into JavaScript behind the Scenes
    React has revolutionized UI development by introducing JSX, a syntax that blends JavaScript with HTML-like elements. While JSX simplifies the process of building components, understanding its inner workings is key to creating scalable and performant applications. This article explores how inline Jav
    9 min read
  • How does inline JavaScript work with HTML ?
    Inline JavaScript refers to JavaScript code embedded directly within HTML elements using the onclick, onmouseover, or other event attributes. This allows you to execute JavaScript code in response to user interactions or specific events without needing a separate JavaScript file or script block. Syn
    2 min read
  • How getElementByID works in JavaScript ?
    The document method getElementById() returns an element object representing the element whose id property matches with the given value. This method is used to manipulate an element on our document & is widely used in web designing to change the value of any particular element or get a particular
    2 min read
  • What are the global objects of Node.js ?
    Node.js is a JavaScript framework based on an open-source project that is used for server-side scripting. Node.js Global Objects are those objects which are present in all modules. Global Objects can be used directly in the application which is available without importing any module. Global objects
    5 min read
  • How JavaScript Works?
    JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive f
    14 min read
  • How TypeScript Compilation Works?
    TypeScript is a superset of JavaScript that adds type safety to your code. It compiles into plain JavaScript, allowing it to run in any JavaScript environment. The TypeScript compiler (tsc) checks the code for errors and then converts it into JavaScript. During this process, all TypeScript-specific
    4 min read
  • What is the Relationship between Node.js and V8 ?
    Node.js and V8 are closely related, with V8 being a fundamental component of Node.js that significantly influences its capabilities and performance. Understanding their relationship involves delving into the roles each plays and how they interact within the context of server-side JavaScript executio
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences