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:
- Single-threaded
- Non-Blocking, Asynchronous I/O
- Cross-platform
- Fast Execution (V8 Engine)
- Real-Time Data Handling.
Node.js Interview Questions for Freshers
1. How does Node.js work?
Node.js works on a single-threaded, event-driven architecture using the V8 JavaScript engine.
- V8 Engine: Compiles JavaScript into fast machine code.
- Event Loop: Handles asynchronous tasks (I/O, timers, requests) without blocking the main thread.
- Libuv library: Provides a thread pool and handles background tasks like file system operations and networking.
- Non-blocking I/O: Lets Node.js process thousands of concurrent requests efficiently without creating multiple threads
2. What is NPM?
NPM stands for Node Package Manager. It is used in Node.js to install and manage packages (libraries or dependencies) required for JavaScript applications.
- Uses package.json to manage project dependencies and metadata.
- Works through CLI commands like npm install, npm update, and npm uninstall.
3. Why is Node.js single-threaded?
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.
4. If Node.js is single-threaded, then how does it handle concurrency?
Node.js is single-threaded, but it can handle concurrency efficiently through its event-driven, non-blocking I/O model.
- Node.js uses a single-threaded event loop to handle requests.
- I/O operations run asynchronously, so other tasks continue without blocking.
- Completed tasks add callbacks to a queue, which the event loop executes.
 5. Why is Node.js preferred over other backend technologies like Java and PHP?
Here are some reasons why Node.js is preferred:
- Fast Performance: Node.js is known for its speed in handling I/O-heavy tasks.
- NPM Ecosystem: Node Package Manager offers over 50,000 bundles to help developers speed up development.
- Real-Time Applications: Perfect for data-intensive, real-time apps as it doesn't wait for APIs to return data.
- Unified Codebase: The Same code is used for both server and client, improving synchronization.
- Easy for JavaScript Developers: Since Node.js is based on JavaScript, web developers can easily integrate it into their projects.
6. What is the difference between Synchronous and Asynchronous functions?
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. |
7. What are the module in Node.js?
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.
8. What is the purpose of the 'require' keyword in Node.js?
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.9. What is V8 engine in Node.js?
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:
- Compiles JavaScript to machine code, enabling fast execution.
- Handles memory management and garbage collection efficiently.
- Provides the core runtime to run JavaScript outside the browser, which Node.js extends with additional APIs.
10. How to handle environment variables in Node.js?
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:
npm install dotenv
Use .env file with dotenv:
require('dotenv').config();
const port = process.env.PORT || 3000;
11. What is control flow in Node.js?
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.
12. What do you mean by event loop in Node.js?
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:
console.log("Start");
setTimeout(() => {
console.log("Timeout callback");
}, 0);
console.log("End");
13. What is the order in which control flow statements get executed?
The order in which the statements are executed is as follows:
- Execution and queue handling
- Collection of data and storing it
- Handling concurrency
- Executing the next lines of code
14. What are the main disadvantages of Node.js?
Here are some main disadvantages of Node.js listed below:
- Single-threaded nature: It may not fully utilize multi-core CPUs, limiting performance.
- NoSQL preference: Relational databases like MySQL aren't commonly used.
- Rapid API changes: Frequent updates can introduce instability and compatibility issues.
15. What is REPL in Node.js?
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.
- Read: It reads the input provided by the user (JavaScript expressions or commands).
- Eval: It evaluates the input (executes the code).
- Print: It prints the result of the evaluation to the console.
- Loop: It loops back, allowing you to enter more code and get immediate results.
16. How to import a module in Node.js?
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:
- CommonJS (default):
const fs = require('fs'); // Built-in module
const add = require('./math'); // Custom module
- ES Modules (modern):
import fs from 'fs';
import { add } from './math.js';
17. What is the difference between Node.js and Angular?
| 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. |
18. What is package.json in Node.js?
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"
}
}19. How to create the simple HTTP server in Node.js?
You can create a simple HTTP server in Node.js using the built-in http module:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
Output:
node app.js
20. What are the most commonly used libraries in Node.js?
There are the two most commonly used libraries in Node.js:
- ExpressJS: ExpressJS is a minimal and flexible web application framework for building robust APIs and web apps. It simplifies routing, middleware handling, and request/response management.
- Mongoose: An Object Data Modeling (ODM) library for MongoDB and Node.js, it helps in managing data relationships, schema validation, and business logic.
21. What are promises 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.
22. How do you install, update, and delete a dependency?
- Install the Dependencies

- Update the Dependencies

- Delete the Dependencies

23. Which command used to import external libraries?
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');Node.js Interview Questions for Intermediate
24. What is event-driven programming in Node.js?
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:
- A callback function ( called an event handler) is called when an event is triggered.
- An event loop that listens for event triggers and calls the corresponding event handler for that event.
25. What is a buffer in Node.js?
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.
26. What are streams in Node.js?
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:
- Readable Streams: These streams allow you to read data. For example, reading data from a file or receiving HTTP request data.
Example:
fs.createReadStream() or http.IncomingMessage.- Writable Streams: These streams allow you to write data. For example, writing data to a file or sending HTTP response data.
Example:
fs.createWriteStream() or http.ServerResponse.- Duplex Streams: These are both readable and writable. You can both read and write data using the same stream. Example: A TCP socket.
- Transform Streams: These are a type of duplex stream where the data is transformed as it is read and written. Example: A zlib stream to compress or decompress data.
27. Explain the crypto module in Node.js.
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.
28. What is callback hell?
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.
29. Explain the use of the timers module in Node.js.
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, ...]);- callback: The function to be executed after the delay.
- delay: The time in milliseconds after which the function is executed.
- [arg1, arg2, ...]: Optional arguments that can be passed to the callback function.
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, ...]);- callback: The function to be executed.
- [arg1, arg2, ...]: Optional arguments to pass to the callback function.
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, ...]);- callback: The function to be executed repeatedly.
- delay: The time in milliseconds between each execution.
- [arg1, arg2, ...]: Optional arguments that can be passed to the callback function.
30. Difference between setImmediate() and process.nextTick() methods
| 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 |
31. What are the different types of HTTP requests?
The different types of HTTP requests are mentioned below:
- GET: Retrieve data.
- POST: Create new resource.
- PUT: Update an entire resource.
- PATCH: Partially update a resource.
- DELETE: Remove a resource.
32. What is the difference between spawn() and fork() method?
| 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 |
33. Explain the use of the passport module in Node.js
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.
34. What is a fork in Node.js?
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.
35. What are the three methods to avoid callback hell?
The three methods to avoid callback hell are:
- Using async/await()
- Using promises
- Using generators
36. What is a .body-parser in Node.js?
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.
37. What is CORS in Node.js?
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.
38. Explain the tls module in Node.js.
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.
39. Can you access DOM in Node?
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.
40. How do you manage packages in your Node.js project?
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.Â
41. What is the purpose of NODE_ENV?
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.
42. What is a test pyramid in Node.js?
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:
- Unit Tests (Base): Test individual components or functions in isolation. These tests are fast and numerous.
Example: Testing a single function like add(1, 2). - Integration Tests (Middle): Test interactions between components to ensure they work together. These are slower than unit tests but cover more functionality.
Example: Testing API routes to ensure they connect properly with the database. - End-to-End Tests (Top): Test the entire application flow from the user interface to the backend. These are slow and fewer in number.
Example: Simulating user login and navigating the application.
Node.js Interview Questions for Experienced
43. What is piping in Node.js?
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.
44. What is a cluster 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.
45. Explain some of the cluster methods in Node.js
- Fork():Â It creates a new child process from the master. The isMaster returns true if the current process is master or else false.
- isWorker:Â It returns true if the current process is a worker or else false.
- process:Â It returns the child process which is global.
- send():Â It sends a message from worker to master or vice versa.Â
- kill():Â It is used to kill the current worker.
46. How to manage sessions in Node.js?
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.
47. How many types of API functions are there in Node.js?
There are two types of API functions:
- Asynchronous, non-blocking functions - mostly I/O operations which can be fork out of the main loop.
- Synchronous, blocking functions - mostly operations that influence the process running in the main loop.
48. How can we implement authentication and authorization in Node.js?
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.
49. Explain the packages used for file uploading in Node.js.the
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.
50. Explain the difference between Node.js and server-side scripting languages like Python
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). |
51. How to Connect Node.js to a MongoDB Database?
To connect to the MongoDB database write the following code after installing the Mongoose package:
const mongoose = require("mongoose");
mongoose.connect("DATABASE_URL_HERE", {
useNewUrlParser: true,
useUnifiedTopology: true
});
52. How to read command line arguments in Node.js?
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.
let arguments = process.argv ;
console.log(arguments) ;
Step 2: Run the index.js file using the below command:
node index.js
53. Explain the Node.js Redis module.
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.
54. What is web socket?
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.
55. Explain the util module in Node.js
The Util module in Node.js provides access to various utility functions. There are various utility modules available in the Node.js module library.
- OS Module:Â Operating System-based utility modules for Node.js are provided by the OS module.Â
- Path Module:Â The path module in Node.js is used for transforming and handling various file paths.Â
- DNS Module:Â DNS Module enables us to use the underlying Operating System name resolution functionalities. The actual DNS lookup is also performed by the DNS Module.Â
- Net Module:Â Net Module in Node.js is used for the creation of both client and server. Similar to DNS Module this module also provides an asynchronous network wrapper.
56. Explain DNS module in Node.js
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.
57. What is the difference between setImmediate() and setTimeout()?
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. |
58. What is an Event Emitter in Node.js?
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.