Nodejs Lesson 15: Internals of Nodejs: LibUV (2024)

1

By Mohammad Shad Mirza Follow 23,870 February 4, 2021 Follow

Category:

Node.js

Node.js Lessons

Programming

Nodejs Lesson 15: Internals of Nodejs: LibUV (2)

Nodejs Lesson 15: Internals of Nodejs: LibUV

Hello everyone, today we are going to talk about the internals of Nodejs. This article will guide how node js works and how it can handle async tasks. What will happen if ten requests come at once? Will it handle one request and discard the other 9? or will it create a queue and serve each one by one. We will answer all these questions in this and coming lesson. Let’s start.

The main engine behind Nodejs: LibUV

LibUV is the core engine that powers Nodejs. LibUV provides support for asynchronous I/O operations. It’s a C based library primarily created for Nodejs and used by Luvit, Julia, pyuv, and some other software.

LibUV enforces an asynchronous, event-driven style of programming. It uses event loops to handle asynchronous tasks effectively. It also supports non-blocking network support, asynchronous file system access, etc.

By “event-driven” programming, we mean it watches for events to occur and then handle them when they occur. As we saw in the Event Emitter lesson earlier, we created an event listener who was “listening” to the event. We then wrote a handler function, which got called when that particular event occurs. The monitoring of events happening in the system is managed by LibUV using something that we call Event Loop. This Event Loop usually keeps running forever.

The responsibilities of LibUV are cross-platform input-output operations, handling files & networks, and support the event loop. You’re not going to interact with these yourself. Still, this knowledge is good to have to understand the working of Nodejs better. We will learn about Event Loops in the next lesson so let’s know the other now.

A few essential concepts in LibUV

To understand LibUV better, we will have to understand the following three concepts first and then about more on LibUV by keeping these three in mind.

LibUV provides two abstractions to work with: handles and requests.

  1. Handles: Handles represent long-lived objects capable of performing certain operations while active. When it completes the job, handles will invoke the corresponding callbacks. As long as a handle is active, the event loop will continue running. Some examples of handles are TCP servers that get their connection callback called every time there is a new connection, timers, signals, and child processes.
  2. Requests: Abstractions for short-lived operations. In contrast to handles that are considered as objects, requests can be thought of as functions or methods. Requests are used to write data on handles. Like handles, active requests will also keep the event loop alive.Another essential concept in LibUV is thread pool. LibUV delegates all the heavy work to a pool of worker threads.
  3. Thread pool: The thread pool takes care of the file I/O and DNS lookup. All the callbacks, however, are executed on the main thread. Since Node 10.5, worker threads can also be used by the programmer to run Javascript in parallel.

More on working with threads in LibUV

The libuv module has a responsibility that is relevant for some particular functions in the standard library. For some standard library function calls, the node C++ side and libuv decide to do expensive calculations outside of the event loop entirely. LibUV creates something called a thread pool. This thread pool consists of four threads by default. These threads can be used for running computationally intensive tasks such as hashing functions. Many of the functions included in the standard node library will automatically make use of this thread pool.

If you have too many function calls, It will use all of the cores. CPU cores do not actually speed up the processing function calls. They allow for some amount of concurrency inside of the work that you are doing.

libuv doesn’t use thread for asynchronous tasks, but for those that aren’t asynchronous by nature. As an example, it doesn’t use threads to deal with sockets. It uses threads to make synchronous fs calls asynchronous.

The I/O (or event) loop is the central part of libuv. It establishes the content for all I/O operations, and it’s meant to be tied to a single thread. One can run multiple event loops as long as each runs in a different thread.

LibUV helps in handling:

  1. File I/O includes file watching, file system operations, etc
  2. Child processes (the child-process module in Node)
  3. A pool of worker threads to handle blocking I/O tasks
  4. Synchronization primitives for threads.

Let us look at what’s happening at launching a server of this kind as an example:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

const http = require('http');

const fs = require('fs');

const server = new http.Server();

server.on('request', (req, info) => {

if (req.url == '/') {

fs.readFile('index.html', function(err, info) {

if(err) {

console.error(err);

res.statusCode = 500;

res.end("A server error occurred ");

return

}

res.end("info");

});

} else { /*404 */ }

});

server.listen(3000);

First JavaScript gets active. It connects the modules:

JavaScript

1

2

const http = require('http');

const fs = require('fs');

and it creates an object

JavaScript

1

const server = new http.createServer();

It gives a handler:

JavaScript

1

server.on('request', (err, info) => {});

At this point, it doesn’t matter what is inside the function because a handler hasn’t been activated yet. The last string is a call for the “listen” command.

JavaScript

1

server.listen(3000);

Getting to Node.js, the command goes through its C++ code and becomes an internal method callTCPWrap::listen. This internal method callsuv__listen, which executes the whole work.

Nodejs Lesson 15: Internals of Nodejs: LibUV (3)

LibUV working

Depending on an operational system, it hangs a connection handler on this port. For instance, the Unix system requires a system call “listen.” So, LibUV appoints a connection handler for this port. This action’s result gets upwards in the chain. That’s it for today. We will learn about Event Loops in the next lesson.

Source code of the lesson you can find by the link.

About the author

Mohammad Shad Mirza

Registered 11-12-2019 | Last seen 8 months ago 72

4 Comments | 31 Publications

Vacancies
Nodejs Lesson 15: Internals of Nodejs: LibUV (2024)

FAQs

Does NodeJS use libuv? ›

Central to this prowess is a lesser-known but crucial component: `libuv`. This multi-platform support library is the backbone of Node. js's non-blocking I/O operations, a feature that has made Node. js immensely popular for server-side development.

Is libuv C or c++? ›

libuv is a multi-platform C library that provides support for asynchronous I/O based on event loops. It supports epoll(4) , kqueue(2) , Windows IOCP, Solaris event ports and Linux io_uring.

How does libuv work under the hood? ›

1. **Event-Driven:** Libuv is primarily an event-driven library. It manages events such as I/O operations, timers, and other asynchronous tasks. It uses an event loop to monitor events and execute associated callbacks when events occur.

How does libuv work? ›

libuv enforces an asynchronous, event-driven style of programming. Its core job is to provide an event loop and callback based notifications of I/O and other activities. libuv offers core utilities like timers, non-blocking networking support, asynchronous file system access, child processes and more.

How many threads does libuv use? ›

By default, Libuv uses 4 threads to handle the operations and tasks. It reduces the workload of synchronous operations and avoids blocking tasks unnecessarily. We can use any number of threads up to 1024 and it also depends on the performance parameter of the system.

How many threads does libuv have? ›

By default, libuv uses a thread pool with 4 threads, but this number can be changed by setting the UV_THREADPOOL_SIZE environment variable. This means that you can increase or decrease the number of threads in the thread pool depending on the requirements of your application.

Does libuv use threads? ›

libuv also uses threads to allow you, the application, to perform a task asynchronously that is actually blocking, by spawning a thread and collecting the result when it is done. Today there are two predominant thread libraries: the Windows threads implementation and POSIX's pthreads(7).

Is libuv multithreaded? ›

Libuv creates a pool with four threads (Thread Pool) that are only used if no async API is available. So, as you can see, Libuv makes multi-threading possible out of the box.

Is libuv single threaded? ›

libuv uses a thread pool to make asynchronous file I/O operations possible, but network I/O is always performed in a single thread, each loop's thread. While the polling mechanism is different, libuv makes the execution model consistent across Unix systems and Windows.

Is event loop part of libuv? ›

The event loop is part of libuv's but the event loop definition in libuv is so confusing. If there are no events then the event-loop exits, which stops the program. Because blocking functions are already executed.

What are the benefits of libuv library? ›

Benefits of libuv
  • Non-Blocking I/O: Libuv provides non-blocking I/O, which lets Node. ...
  • Performance: The efficient implementation and use of platform-specific APIs by Libuv boost Node. ...
  • Cross-Platform support: The cross-platform nature of Libuv makes Node.

What are the features of node js library libuv? ›

Features
  • Full-featured event loop backed by epoll, kqueue, IOCP, event ports.
  • Asynchronous TCP and UDP sockets.
  • Asynchronous DNS resolution.
  • Asynchronous file and file system operations.
  • File system events.
  • ANSI escape code controlled TTY.
  • IPC with socket sharing, using Unix domain sockets or named pipes (Windows)

Does Python use libuv? ›

pyuv is a Python module which provides an interface to libuv. libuv is a high performance asynchronous networking library, used as the platform layer for NodeJS.

Does V8 use libuv? ›

Since V8 lacks its own event loop, when an asynchronous function is encountered, it is not directly executed on the call stack. Instead, V8 forwards the function to either the libuv API or Chrome's internal event loop, depending on where the script is executed.

What is a thread pool in NodeJS? ›

Thread Pool: All heavy lifting is delegated to a pool of worker threads by Libuv. The file I/O and DNS lookup are handled by the thread pool. However, all callbacks are executed on the main thread. As with Node 10.5, the programmer can additionally use worker threads to run Javascript concurrently.

Who uses libuv? ›

Welcome to the libuv documentation

It was primarily developed for use by Node. js, but it's also used by Luvit, Julia, uvloop, and others.

What encoding does Node.js use? ›

Node.js buffers accept all case variations of encoding strings that they receive. For example, UTF-8 can be specified as 'utf8' , 'UTF8' , or 'uTf8' . The character encodings currently supported by Node.js are the following: 'utf8' (alias: 'utf-8' ): Multi-byte encoded Unicode characters.

What code does Node.js use? ›

JavaScript is the only language that Node.js supports natively, but many compile-to-JS languages are available. As a result, Node.js applications can be written in CoffeeScript, Dart, TypeScript, ClojureScript and others.

Which js engine does node use? ›

V8 was chosen to be the engine that powered Node.js back in 2009, and as the popularity of Node.js exploded, V8 became the engine that now powers an incredible amount of server-side code written in JavaScript. The Node.js ecosystem is huge and thanks to V8 which also powers desktop apps, with projects like Electron.

Top Articles
When is it legal to film people without their permission? — Stream Semester
19 month old sleep schedule: Bedtime and nap schedule
Use Copilot in Microsoft Teams meetings
Printable Whoville Houses Clipart
Design215 Word Pattern Finder
Urist Mcenforcer
Fat People Falling Gif
Vanadium Conan Exiles
Student Rating Of Teaching Umn
Camstreams Download
Globe Position Fault Litter Robot
Jscc Jweb
Connect U Of M Dearborn
Daily Voice Tarrytown
Sam's Club La Habra Gas Prices
Google Flights Missoula
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
Convert 2024.33 Usd
Www Craigslist Milwaukee Wi
Lakers Game Summary
Gazette Obituary Colorado Springs
Seeking Arrangements Boston
Engineering Beauties Chapter 1
Inbanithi Age
1145 Barnett Drive
Busted Mugshots Paducah Ky
As families searched, a Texas medical school cut up their loved ones
Proto Ultima Exoplating
How to Draw a Bubble Letter M in 5 Easy Steps
Solve 100000div3= | Microsoft Math Solver
Gideon Nicole Riddley Read Online Free
Weekly Math Review Q4 3
Carespot Ocoee Photos
Telegram update adds quote formatting and new linking options
The Minneapolis Journal from Minneapolis, Minnesota
Orion Nebula: Facts about Earth’s nearest stellar nursery
Kerry Cassidy Portal
Topos De Bolos Engraçados
Electronic Music Duo Daft Punk Announces Split After Nearly 3 Decades
Mid America Irish Dance Voy
Join MileSplit to get access to the latest news, films, and events!
Craigslist Pets Plattsburgh Ny
Emily Tosta Butt
Rs3 Nature Spirit Quick Guide
Expendables 4 Showtimes Near Malco Tupelo Commons Cinema Grill
Love Words Starting with P (With Definition)
Swsnj Warehousing Inc
6463896344
The Plug Las Vegas Dispensary
How To Find Reliable Health Information Online
La Fitness Oxford Valley Class Schedule
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated:

Views: 5959

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.