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:
Node.js Inspector
Next article icon

Libuv in Node.js

Last Updated : 10 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Node.js relies on various dependencies under the hood for providing various features.

  • V8
  • libuv
  • llhttp
  • c-ares
  • OpenSSL

Libuv is one of them, let’s discuss libuv in detail.

Libuv

libuv is a C library originally written for Node.js to abstract non-blocking I/O operations. 

  • Event-driven asynchronous I/O model is integrated.
  • It allows the CPU and other resources to be used simultaneously while still performing I/O operations, thereby resulting in efficient use of resources and network.
  • It facilitates an event-driven approach wherein I/O and other activities are performed using callback-based notifications.

Example: If a program is querying the database, the CPU sits idle until the query is processed and the program stays at a halt, thereby causing wastage of system resources. To prevent this, libuv is used in Node.js which facilitates a non-blocking I/O.

It also has mechanisms to handle services like File System, DNS, network, child processes, pipes, signal handling, polling, and streaming.
To perform blocking operations that can’t be done asynchronously at OS level, libuv also includes a thread pool to distribute CPU loads. 

  • What is a thread pool?

Libuv assigns tasks to a pool of worker threads. However, all callbacks that occur on task completion are executed on the main thread. 
Note: After Node 10.5 worker threads can also be used to execute JavaScript in parallel. Libuv uses 4 threads by default, but can be changed using the UV_THREADPOOL_SIZE 

process.env.UV_THREADPOOL_SIZE = 5

Features of libuv:

  • Full-featured event loop backed by epoll (Linux), kqueue (OSX), IOCP (Windows), event ports (SunOS).
  • Asynchronous TCP (net module) and UDP (dgram module)
  • Asynchronous DNS resolution (used partly for the dns module)
  • Asynchronous file, file system operations & events (fs module)
  • ANSI escape code controlled TTY
  • Thread pool and Signal handling
  • Child processes
  • High-resolution clock
  • Threading and synchronization primitives.
  • Inter-Process Communication using sockets and Unix domain sockets (Windows)

Event or I/O loop:

Event or I/O loop uses a single threaded asynchronous I/O approach, hence it is tied to a single thread. In order to run multiple event loops, each of these event loops must be run on a different thread. It is not thread-safe by default with some exceptions. 

Libuv maintains an Event queue and event demultiplexer. The loop listens for incoming I/O and emits event for each request. The requests are then assigned to specific handler (OS dependent). After successful execution, registered callback is enqueued in event queue which are continuously executed one by one. 
Note: The current time required during entire process is cached by libuv at beginning of each iteration of loop to minimize frequent system calls.

Example: If a network request is made, a callback is registered for that request, and the task is assigned to the handler. Until it is performed other operations carry on. On successful execution/termination, the registered callback is en-queued in the event queue which is then executed by the main thread after the execution of previous callbacks already present in the queue.

It uses platform-specific mechanisms as mentioned earlier to achieve the best compatibility and performance epoll (Linux), kqueue (OSX), IOCP (Windows), event ports (SunOS).

File I/O:

File I/O is implemented in libuv using a global thread pool on which all loops can queue work. It allows disk to be used in an abstracted asynchronous fashion. It breaks down complex operations into simpler operations to facilitate async-like behavior. 

Example: If the program instructs to write a buffer to a specific file, in normal situations, the I/O will be blocked until the operation is successful/terminated. However, libuv abstracts this into an async manner by putting an event notification which would notify about operations success/failure after it is finished, until then the other I/O operations can be performed hassle-free. 
Note: Thread-safety is not assured by libuv (with few exceptions)

Unlike event loop, File I/O uses platform-independent mechanisms. There are 3 kinds of async disk APIs that are handled by File I/O:

  1. linux AIO (supported in kernel)
  2. posix AIO (supported by linux, BSD, Mac OS X, solaris, AIX, etc)
  3. Windows’ overlapped I/O

Benefits:

  • Disk operations are performed asynchronously.
  • High level operations can be broken down to simpler disk operations which facilitate rectifying the information.
  • Disk thread can use vector operations like readv & writev allowing more buffers to be passed.

Reference: http://docs.libuv.org/en/v1.x/design.html



Next Article
Node.js Inspector
author
omkarphansopkar
Improve
Article Tags :
  • Node.js
  • Technical Scripter
  • Web Technologies
  • NodeJS-Questions
  • Technical Scripter 2020

Similar Reads

  • Node.js Inspector
    What is inspector in Node.js? Inspector in node.js is a debugging interface for node.js application that is contained in the app.js file and used blink developer tools. It works almost similar to chrome developer tools. It can support almost all the feature that a debugger generally have such as nav
    3 min read
  • Node.js Basics
    NodeJS is a powerful and efficient open-source runtime environment built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server side, which helps in the creation of scalable and high-performance web applications. In this article, we will discuss the NodeJs Basics and
    7 min read
  • How to Install Node.js on Linux
    Installing Node.js on a Linux-based operating system can vary slightly depending on your distribution. This guide will walk you through various methods to install Node.js and npm (Node Package Manager) on Linux, whether using Ubuntu, Debian, or other distributions. PrerequisitesA Linux System: such
    6 min read
  • Source Mapping in Node.js
    In this article, we will learn about the source mapping techniques that happen in the Node.js web framework that uses JavaScript. The source maps basically represent the data transmission file from the source of origin of the message to the target destination of the function. The JSON files in the J
    4 min read
  • Node.js Console
    The console module is essential for debugging and logging in Node.js applications. It enables developers to print messages to the terminal, making it easier to monitor application behavior, track issues, and display runtime information. Console in Node.js The console module in Node.js is a built-in
    4 min read
  • What are Modules in Node.js ?
    In Node.js Application, a Module can be considered as a block of code that provide a simple or complex functionality that can communicate with external application. Modules can be organized in a single file or a collection of multiple files/folders. Almost all programmers prefer modules because of t
    5 min read
  • What are modules in Node JS ?
    In NodeJS, modules are encapsulated units of code that can be reused across different parts of an application. Modules help organize code into smaller, manageable pieces, promote code reusability, and facilitate better maintainability and scalability of NodeJS applications. Types of Modules:Core Mod
    2 min read
  • Node.js V8 Module
    The v8 module in Node.js is a core module that provides an interface to interact with the V8 JavaScript engine, which is the engine that Node.js uses to execute JavaScript code. This module exposes a variety of V8-specific APIs that allow developers to manage memory usage, optimize performance, and
    5 min read
  • Node.js VM Module
    The VM (Virtual Machine) module in Node.js lets you safely run JavaScript code in a separate, isolated environment. This feature is especially handy when you need to execute code without affecting the rest of your application, making it ideal for handling untrusted code or creating distinct executio
    4 min read
  • Node.js OS
    The os module in Node.js provides operating system-related utility methods and properties. It helps retrieve system information such as CPU details, memory usage, and network interfaces, enabling you to write system-aware applications. It provides functions to interact with the operating system. It
    3 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