The Wayback Machine - https://web.archive.org/web/20240914073434/https://www.geeksforgeeks.org/demultiplexer-in-nodejs/
Open In App

Demultiplexer in Node.js

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The concept of a demultiplexer in Node.js is based on how Node.js handles its asynchronous operations and event-driven architecture. The demultiplexer, often part of the underlying infrastructure, is key to how Node.js efficiently manages I/O operations and concurrency.

Demultiplexer in Node.js

In digital circuits, a demultiplexer (or “demux”) is a device that takes a single input signal and routes it to one of several outputs. In Node.js, the idea is adapted to manage I/O operations and events. The Event Demultiplexer in Node.js operates within the Reactor pattern—a core architectural design that enables non-blocking, asynchronous I/O.

Node.js uses an event-driven architecture where multiple I/O tasks can be handled concurrently, even if running on a single thread. The Event Demultiplexer is an important component of this architecture. It basically manages all pending I/O operations, listens for their completion, and notifies the event loop to process them.

The Reactor Pattern and Event Demultiplexer

The Reactor pattern is the backbone of Node.js, and the Event Demultiplexer is an important part of this pattern. Here’s how the Reactor pattern functions in Node.js:

  • I/O Request Submission: When a Node.js application initiates an I/O operation (like reading from a file or querying a database), it doesn’t wait for the operation to complete. Instead, it submits the request to the Event Demultiplexer along with a callback function that should be executed once the operation is done.
  • Event Queue Management: The Event Demultiplexer listens to the status of these I/O operations. Once an operation completes, it pushes the event associated with that operation into an event queue.
  • Event Loop Processing: The Event Loop, which constantly monitors the event queue, picks up these events and triggers the corresponding callback functions.

This model allows Node.js to be asynchronous and non-blocking. It can manage multiple I/O operations concurrently without waiting for any specific task to complete before starting a new one.

Role of libuv in Node.js

At the core of Node.js’s I/O handling lies libuv, a multi-platform support library with a focus on asynchronous I/O. It abstracts the event demultiplexer logic, making Node.js compatible with different operating systems.

Each operating system has its own mechanism for handling I/O events. For instance:

  • Linux uses epoll
  • macOS uses kqueue
  • Windows uses IOCP

libuv normalizes these differences and exposes a unified API, allowing Node.js to function consistently across platforms.

How the Event Demultiplexer Works?

The demultiplexer acts as the intermediary between the application and the operating system’s event handling mechanism. Here’s a step-by-step breakdown of how it operates:

  • I/O Request is Submitted: The application submits an asynchronous I/O request to the Event Demultiplexer, along with a callback function.
  • Blocking and Waiting: The Event Demultiplexer monitors multiple resources (like file systems or network connections). It blocks and waits until one or more I/O operations complete.
  • Event Queuing: Once an I/O operation finishes, the Event Demultiplexer pushes the event (along with its handler) into the event queue.
  • Event Loop Iteration: The Event Loop picks up events from the queue and invokes the appropriate handlers (callbacks).
  • Repeat Process: The cycle continues until all events are processed, and the application exits when there are no pending tasks.

Why is the Event Demultiplexer Important?

The Event Demultiplexer allows Node.js to achieve non-blocking I/O while maintaining high performance even when handling thousands of concurrent connections. It’s the main reason why Node.js is well-suited for real-time applications, such as chat applications, gaming servers, and live streaming platforms.

Advantages of Using the Event Demultiplexer in Node.js

  • Scalability: Node.js can handle multiple I/O operations concurrently without creating a new thread for each operation.
  • Efficiency: The single-threaded nature of Node.js ensures low memory usage, as additional threads are not spawned for each request.
  • Performance: By utilizing the Event Demultiplexer, Node.js can perform I/O operations faster by reducing blocking times and efficiently utilizing system resources.

Previous Article
Next Article

Similar Reads

Uses of Demultiplexer in Node.js
A demultiplexer in Node.js is a concept or tool used to route or distribute data or requests to various handlers based on certain criteria, similar to how a traditional demultiplexer works in digital circuits by taking a single input signal and routing it to one of several outputs. In the context of Node.js, demultiplexers can be used to manage and
4 min read
Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.js. The 3 Best Packages of Node.js that you should
4 min read
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications. In this article, we'll explore how to connect a Node.js application with a MySQL database, covering the necessary setup, configuration, and basic
2 min read
How to resolve 'node' is not recognized as an internal or external command error after installing Node.js ?
Encountering the error message ‘node’ is not recognized as an internal or external command after installing Node.js can be frustrating, especially when you’re eager to start working on your project. This error usually means that your system cannot find the Node.js executable because the path to it is not set correctly in your system's environment v
2 min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10->8
5 min read
How to resolve unhandled exceptions in Node.js ?
There are two approaches to resolve unhandled exceptions in Node.js that are discussed below: Approach 1: Using try-catch block: We know that Node.js is a platform built on JavaScript runtime for easily building fast and scalable network applications. Being part of JavaScript, we know that the most prominent way to handle the exception is we can ha
2 min read
HTTP Cookies in Node.js
Cookies are small data that are stored on a client side and sent to the client along with server requests. Cookies have various functionality, they can be used for maintaining sessions and adding user-specific features in your web app. For this, we will use cookie-parser module of npm which provides middleware for parsing of cookies. First set your
4 min read
Node.js String Decoder Complete Reference
The string Decoder module provides an API for decoding Buffer objects into strings. Example: C/C++ Code // Node.js program to demonstrate the // stringDecoder.write() Method // Import the string_decoder module // and get the StringDecoder class // using object destructuring const { StringDecoder } = require("string_decoder"); // Create a
1 min read
Node.js urlObject.hash API
Before we go on to learn about URL objects API we need to know a brief about URL. If you ever wanted to provide utilities so as to parse or resolute your URL, we can do it through the URL Module. We can divide the URL Module into two parts:- These are- URL String and URL Object. The urlObjectHash is a part of URL Object which is generally based on
1 min read
Node.js URLSearchParams.has() Method
In URLSearchParams interface, the has() method returns a Boolean which tells us that if the parameter with input name exists it will return true, else false. Syntax: var Bool = URLSearchParams.has(name) Returns: True - if name present, else it will return False. Parameters: name - Input the name of the parameter. Example1: let url = new URL('https:
1 min read
How to remove all Global Modules in Node.js ?
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside of a browser. You need to remember that Node.js is not a framework and it’s not a programming language. Most of the people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services
2 min read
Node.js hmac.update() Method
The hmac.update() method is an inbuilt method of class HMAC within the crypto module which is used to update the data of hmac object. Syntax: hmac.update(data[, inputEncoding])Parameters: This method takes the following two parameters: data: It can be of string, Buffer, TypedArray, or DataView type. It is the data that is passed to this function.in
2 min read
Node.js process.send() Method
The process.send() method is an inbuilt application programming interface of the process module which is used by the child process to communicate with the parent process. This method does not work for the root process because it does not have any parent process. Syntax: process.send(message, [sendHandle])Parameters: This method accepts the followin
2 min read
Node.js writeStream.clearLine() Method
The writeStream.clearLine() is an inbuilt application programming interface of class WriteStream within the module which is used to clear the current line of this write stream object. Syntax: writeStream.clearLine(dir[, callback]) Parameters: This method takes the following argument as a parameter: dir: Integer value defining the selection of a lin
2 min read
Node.js net.SocketAddress() Method
Node.js Net module allows you to create TCP or IPC servers and clients. A TCP client initiates a connection request to a TCP server to establish a connection with the server. Syntax: Below is the syntax for importing the Net module into your node js project: const <Variable_Name> = require('node:net'); const Net_Module = require('node:net');
3 min read
Node.js fs.link() Method
The fs.link() method is used to create a hard link to the given path. The hard link created would still point to the same file even if the file is renamed. The hard links also contain the actual contents of the linked file. Syntax: fs.link( existingPath, newPath, callback ) Parameters: This method accepts three parameters as mentioned above and des
2 min read
Node Jimp | flip
The flip() function is an inbuilt function in Nodejs | Jimp which flips the image horizontally or vertically. The default settings are to flip the image horizontally. Syntax: flip(h, v, cb) Parameter: h: This parameter takes a boolean value, if true the image will be flipped horizontally.v: This parameter takes a boolean value, if true the image wi
2 min read
How to use SSL/TLS with Node.js ?
TLS/SSL is used for establishing secure connections over the internet. Today, most websites use HTTPS to communicate with clients. HTTPS is basically HTTP running over TLS/SSL. Web clients like browsers alert users about websites that do not use HTTPS since such websites are vulnerable to cyber-attacks. As a result, people refrain from visiting suc
5 min read
Run Python script from Node.js using child process spawn() method
Node.js is one of the most adopted web development technologies but it lacks support for machine learning, deep learning and artificial intelligence libraries. Luckily, Python supports all these and many more other features. Django Framework for Python can utilize this functionality of Python and can provide support for building new age web applica
3 min read
Async Await in Node.js
Before Node version 7.6, the callbacks were the only official way provided by Node to run one function after another. As Node architecture is single-threaded and asynchronous, the community devised the callback functions, which would fire (or run) after the first function (to which the callbacks were assigned) run is completed. Example of a Callbac
2 min read
Node JS | Password Hashing with Crypto module
In real-life applications with User authentication functionality, storing the user passwords as the original string in the database is not practical. Still, it is good practice to hash the password and then store them in the database. Crypto module for Node JS helps developers to hash user passwords. Examples: Original Password : portalforgeeks Has
5 min read
Node.js readStream.isTTY Property
The readStream.isTTY property is an inbuilt application programming interface of class ReadStream within tty module which is used to check if the read stream object is an instance of tty or not. It will always return true for tty, ReadStream. Syntax: const readStream.isTTY Return Value: This property returns true if the read stream object is an ins
2 min read
Node.js date-and-time Date.isLeapYear() Method
The date-and-time.Date.isLeapYear() is a minimalist collection of functions for manipulating JS date and time module which is used to check if the given year is a leap year or not. Required Module: Install the module by npm or used it locally. By using npm: npm install date-and-time --save By using CDN link: <script src="/path/to/date-and-time.m
2 min read
Node.js Http2ServerRequest.httpVersion Method
The Http2ServerRequest.httpVersion is an inbuilt application programming interface of class Http2ServerRequest within the http2 module which is used to get the HTTP version either associated with server or client. Syntax: const request.httpVersion Parameters: This method does not accept any argument as a parameter. Return Value: This method returns
3 min read
Node.js hmac.digest() Method
The hmac.digest() method is an inbuilt application programming interface of class hmac within crypto module which is used to return the hmac hash value of inputted data. Syntax: hmac.digest([encoding])Parameter: This method takes encoding as a parameter which is an optional parameter. Return Value: This method calculates the hmac digest of all data
2 min read
Web technologies Questions | Node.js Quiz | Set-1 | Question 2
How modules in Node.js can be connected from one component to another ? (A) Expose (B) Module (C) Exports (D) All of the above Answer: (C) Explanation: Exports in Node.js are used to export the component from one module to another. It can also export to literal, function, or object. It is responsible for including the JavaScript file into the node.
1 min read
Model-View-Controller(MVC) architecture for Node applications
MVC is an acronym for Model-View-Controller. It is a design pattern for software projects. It is used majorly by Node developers and by C#, Ruby, PHP framework users too. In MVC pattern, application and its development are divided into three interconnected parts. The advantage of this is it helps in focusing on a specific part of the application na
5 min read
Node Jimp | Gaussian
The Gaussian() function is an inbuilt function in Nodejs | Jimp that applies a true Gaussian blur to the image but its processing is quite slow in comparison to other Jimp functions. Syntax: gaussian(r, cb) Parameter: r: This parameter stores the pixel radius of the blur.cb: This is an optional parameter that is invoked when compilation is complete
1 min read