![]() |
VOOZH | about |
Node.js is a JavaScript runtime environment , used as a backend service which is capable of interacting with the operating system. It is mostly used by top companies such as LinkedIn, Netflix, Walmart, Uber, PayPal, NASA, and many more because of its robust features and performance.
Features of Node.js are:
Node.js works on a single-threaded, event-driven architecture using the V8 JavaScript engine.
NPM stands for Node Package Manager. It is used in Node.js to install and manage packages (libraries or dependencies) required for JavaScript applications.
Node.js is single-threaded because it's based on the asynchronous, non-blocking nature of JavaScript. This design makes it simpler to develop and maintain, and it allows Node.js to handle many concurrent requests efficiently.
Node.js is single-threaded, but it can handle concurrency efficiently through its event-driven, non-blocking I/O model.
Here are some reasons why Node.js is preferred:
Here are the differences between Synchronous and Asynchronous functions:
| Synchronous Functions | Asynchronous Functions |
|---|---|
| Blocks the execution until the task completes. | Does not block the execution; allows other tasks to proceed concurrently. |
| Executes tasks sequentially; each task must be completed before the next one starts. | Initiate tasks and proceed with other operations while waiting for completion. |
| Returns the result immediately after completion. | Typically returns a promise or callback or uses event handling to handle the result upon completion. |
| Errors can be easily caught with try-catch blocks. | Error handling is more complex and often involves callbacks, promises, or async/await syntax. |
| Suitable for simple, sequential tasks with predictable execution flow. | Ideal for I/O-bound operations, network requests, and tasks requiring parallel processing. |
In Node.js, a Module is a reusable block of code that provides specific functionality and can be organized in one or multiple files. Modules help simplify applications by dividing code into smaller, manageable parts. Examples include http, fs, os, and path.
The require keyword in Node.js is used to include and import modules (external or built-in) into a Node.js application.
const http = require('http') //imports the HTTP module to create a server.The V8 engine in Node.js is an open-source JavaScript engine developed by Google, written in C++. It is the same engine that powers Google Chrome. In Node.js, the V8 engine:
We use process.env to handle environment variables in Node.js. We can specify environment configurations as well as keys in the .env file. To access the variable in the application, we use the “process.env.VARIABLE_NAME” syntax.
To use it we have to install the dotenv package using the below command:
Use .env file with dotenv:
In Node.js, control flow refers to the order in which asynchronous operations (like file reads, API calls, DB queries) are executed and how their results are handled.
Because, Node.js is non-blocking and event-driven, tasks don’t always finish in the order they start. Control flow ensures they are managed correctly.
The event loop in Node.js is a mechanism that allows it to handle multiple asynchronous tasks concurrently within a single thread. It continuously listens for events and executes associated callback functions.
Example:
The order in which the statements are executed is as follows:
Here are some main disadvantages of Node.js listed below:
REPL in Node.js stands for Read, Evaluate, Print, and Loop. It is a computer environment similar to the shell which is useful for writing and debugging code as it executes the code in on go.
We use the require module to import the External libraries in Node.js. The result returned by require() is stored in a variable, which is used to invoke the functions using the dot notation.
You can import modules in two ways:
| Node.js | Angular |
|---|---|
| Node.js is a server-side runtime environment used to execute JavaScript outside the browser. | Angular is a front-end framework used to build dynamic and interactive user interfaces. |
| It is mainly used for backend development such as APIs, servers, and database communication. | It is mainly used for frontend development to create responsive single-page applications (SPAs). |
| Node.js runs on the server to handle client requests and responses. | Angular runs in the browser to manage the user interface. |
| It uses JavaScript for backend logic and server-side operations. | It primarily uses TypeScript for building structured frontend applications. |
package.json in Node.js is a metadata file that contains project-specific information such as dependencies, scripts, version, author details, and other configuration settings required for managing and building the project.
Example:
{
"name": "app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"express": "^4.21.2"
}
}You can create a simple HTTP server in Node.js using the built-in http module:
Output:
node app.jsThere are the two most commonly used libraries in Node.js:
A Promise in Node.js is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. It is used to handle asynchronous operations more efficiently compared to callbacks. Promises help avoid callback hell by enabling better chaining using .then() and .catch() methods.
In Node.js, you can import external libraries (also known as packages) using the require() function. This allows you to include modules or packages that you have installed via npm (Node Package Manager).
const express = require('express');Event-driven programming is used to synchronize the occurrence of multiple events and to make the program as simple as possible. The basic components of an Event-Driven Program are:
The Buffer class in Node.js is used to perform operations on raw binary data. Generally, Buffer refers to the particular memory location in memory. Buffer and array have some similarities, but the difference is that array can be any type, and it can be resizable. Buffers only deal with binary data, and it can not be resizable. Each integer in a buffer represents a byte. console.log() function is used to print the Buffer instance.
In Node.js, streams are a powerful way to handle data in chunks rather than loading the entire data into memory. Streams allow for the efficient processing of large volumes of data, especially in situations where the data size is too large to fit into memory all at once.
There are four types of the Streams:
fs.createReadStream() or http.IncomingMessage. fs.createWriteStream() or http.ServerResponse.The crypto module is used for encrypting, decrypting, or hashing any type of data. This encryption and decryption basically help to secure and add a layer of authentication to the data. The main use case of the crypto module is to convert the plain readable text to an encrypted format and decrypt it when required.
Callback hell is an issue caused by a nested callback. This causes the code to look like a pyramid and makes it unable to read To overcome this situation, we use promises.
The Timers module in Node.js contains various functions that allow us to execute a block of code or a function after a set period. The Timers module is global, we do not need to use require() to import it.
It has the following methods:
1. setTimeout() method
The setTimeout() function is used to execute a function once after a specified delay (in milliseconds).
setTimeout(callback, delay, [arg1, arg2, ...]);2. setImmediate() method
The setImmediate() function is used to execute a callback function immediately after the current event loop cycle, i.e., after the I/O events in the Node.js event loop have been processed. It is similar to setTimeout() with a delay of 0 milliseconds, but it differs in terms of when the function is executed.
setImmediate(callback, [arg1, arg2, ...]);3. setInterval() method
The setInterval() function is used to execute a function repeatedly, with a fixed time delay between each call.
setInterval(callback, delay, [arg1, arg2, ...]);| setImmediate() | process.nextTick() |
|---|---|
| Executes callback in the check phase of the event loop | Executes callback in the next tick queue |
| Runs after I/O events | Runs before I/O events |
| Scheduled to run on the next iteration of the event loop | Runs immediately after the current operation completes |
| Lower priority than nextTick | Higher priority than setImmediate |
| Does not block I/O operations | Can block I/O if overused |
| Used when you want to run code after I/O tasks | Used for immediate execution after current function |
The different types of HTTP requests are mentioned below:
| spawn() | fork() |
|---|---|
| Used to run any system command | Used specifically to create new Node.js processes |
| Executes external programs | Executes another JavaScript file |
| Does not create communication channel by default | Creates built-in communication channel (IPC) |
| Suitable for running large processes | Suitable for Node-to-Node communication |
| Returns a stream for data handling | Returns an object with messaging support |
| Used for general process execution | Used for creating child Node.js modules |
The passport module is used for adding authentication features to our website or web app. It implements authentication measure which helps to perform sign-in operations.
Fork is a method in Node.js that is used to create child processes. It helps to handle the increasing workload. It creates a new instance of the engine which enables multiple processes to run the code.
The three methods to avoid callback hell are:
Body-parser is the Node.js body-parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it. It is an NPM module that processes data sent in HTTP requests.
The word CORS stands for “Cross-Origin Resource Sharing”. Cross-Origin Resource Sharing is an HTTP-header based mechanism implemented by the browser which allows a server or an API to indicate any origins (different in terms of protocol, hostname, or port) other than its origin from which the unknown origin gets permission to access and load resources. The cors package available in the npm registry is used to tackle CORS errors in a Node.js application.
The tls module provides an implementation of the Transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols that are built on top of OpenSSL. It helps to establish a secure connection on the network.
No, you cannot access the DOM in Node.js because Node.js is a server-side environment, while the DOM (Document Object Model) is a client-side concept used in browsers to interact with HTML and XML documents.
Node.js runs on the server and does not have access to a browser's DOM, which is part of the browser's environment. The DOM allows you to manipulate the content and structure of web pages, but it is not available in Node.js, as it operates on the backend, outside the context of a web page or browser.
In a Node.js project, package management is handled through npm (Node Package Manager), which is the default package manager for Node.js, which allows you to install and manage third-party packages and create and publish your packages.
The NODE_ENV environment variable in Node.js is used to specify the environment in which the Node.js application is running. It helps in distinguishing between different stages of the application's lifecycle, such as development, testing, or production, and allows you to customize the behavior of the application based on that environment.
The Test Pyramid is a strategy for structuring tests in a software project to ensure efficiency, maintainability, and good coverage. It consists of three levels:
In Node.js, piping refers to the process of passing the output of one stream directly into another stream. It allows data to flow through multiple streams without needing to store it in memory or temporarily write it to disk. This is a common pattern used in file handling, HTTP requests, and other I/O operations in Node.js.
Due to a single thread in Node.js, it handles memory more efficiently because there are no multiple threads due to which no thread management is needed. Now, to handle workload efficiently and to take advantage of computer multi-core systems, cluster modules are created that provide us the way to make child processes that run simultaneously with a single parent process.
Session management can be done in Node.js by using the express-session module. It helps in saving the data in the key-value form. In this module, the session data is not saved in the cookie itself, just the session ID.
There are two types of API functions:
Authentication is the process of verifying a user’s identity, while Authorization determines what actions or resources that user is allowed to access. In Node.js, these can be implemented using packages such as Passport (for strategies like OAuth, Google, GitHub, etc.) and JWT(jsonwebtoken) for token-based authentication and role-based authorization.
The package used for file uploading in Node.js is Multer. The file can be uploaded to the server using this module. There are other modules in the market but Multer is very popular when it comes to file uploading. Multer is a Node.js middleware that is used for handling multipart/form-data, which is a mostly used library for uploading files.
Node.js | Server-Side Scripting Languages |
|---|---|
A runtime environment for executing JavaScript outside the browser. | A programming language that can be used for server-side scripting (e.g., Python, PHP, Ruby). |
Built on JavaScript, primarily used for asynchronous programming. | Built on Python, which is synchronous by default, but can also be used for asynchronous programming. |
Non-blocking, event-driven I/O model using the Event Loop. | Thread-based concurrency (multi-threading) or asynchronous programming with frameworks like asyncio. |
Highly performant for I/O-heavy tasks but less efficient for CPU-heavy operations due to single-threaded nature. | More suitable for CPU-heavy operations but can be less performant in handling high concurrency compared to Node.js. |
Used for building fast, scalable, I/O-bound applications (e.g., APIs, real-time apps). | Commonly used for general-purpose programming, web development, and CPU-bound tasks (e.g., Django for web, machine learning with libraries like TensorFlow). |
To connect to the MongoDB database write the following code after installing the Mongoose package:
Command-line arguments (CLI) are strings of text used to pass additional information to a program when an application is running through the command line interface of an operating system. We can easily read these arguments by the global object in node i.e. process object. Below is the approach:
Step 1: Save a file as index.js and paste the below code inside the file.
Step 2: Run the index.js file using the below command:
node index.js
Redis is an Open Source store for storing data structures. It is used in multiple ways. It is used as a database, cache, and message broker. It can store data structures such as strings, hashes, sets, sorted sets, bitmaps, indexes, and streams. Redis is very useful for Node.js developers as it reduces the cache size which makes the application more efficient. However, it is very easy to integrate Redis with Node.js applications.
Web Socket is a protocol that provides full-duplex (multiway) communication i.e. allows communication in both directions simultaneously. Web Socket is a modern web technology in which there is a continuous connection between the user’s browser (client) and the server. In this type of communication, between the web server and the web browser, both of them can send messages to each other at any point in time.
The Util module in Node.js provides access to various utility functions. There are various utility modules available in the Node.js module library.
DNS is a node module used to do name resolution facility which is provided by the operating system as well as used to do an actual DNS lookup. Its main advantage is that there is no need for memorizing IP addresses – DNS servers provide a nifty solution for converting domain or subdomain names to IP addresses.
steImmediate() | setTimeout() |
|---|---|
Executes the callback immediately after the current event loop phase. | Executes the callback after the specified delay (in ms). |
Adds the callback to the next iteration of the event loop, in the check phase. | Adds the callback to the timer queue, to be executed after the specified delay. |
Has no timer; it is designed for immediate execution. | Executes only after the specified delay, which may vary slightly based on system timing resolution. |
No delay, always executes after the current phase finishes. | Executes after the specified delay (minimum of 1 ms). |
Used for callbacks that need to run immediately after I/O events or timers. | Used for delaying the execution of a callback by a specific time. |
In Node.js, an Event Emitter is a class that allows objects to emit events and register listeners (callbacks) to handle those events. It is part of the events module and is commonly used to handle asynchronous events and to implement an observer pattern, where an object (the emitter) triggers events, and other objects (listeners) respond to those events.