NodeJS is one of the most popular runtime environments, known for its
efficiency, scalability, and ability to handle asynchronous operations. It is
built on Chrome’s V8 JavaScript engine for executing JavaScript code
outside of a browser. It is extensively used by top companies such as
LinkedIn, Netflix, Walmart, Uber, PayPal, NASA, and many more because
of its robust features and performance.
In this guide, we will provide 60+ NodeJS Interview Questions and
Answers 2025 designed for freshers and experienced professionals with
3, 5, and 8 years of experience. Here, we cover everything, including core
NodeJS concepts, asynchronous programming, event-driven architecture,
error handling, design patterns, NodeJS, and more, that will surely help
you to crack NodeJS interviews.
NodeJS Interview Questions for Freshers
In this section, we will discuss basic NodeJS questions asked in the
interview suitable for freshers.
1. What is NodeJS?
NodeJS is an open-source, cross-platform JavaScript runtime environment
engine used for executing JavaScript code outside the browser. It is built
on Google Chrome's V8 JavaScript engine. Some of the key features of
NodeJS are mentioned below:
● Single-threaded
● Non-Blocking, Asynchronous I/O
● Cross-platform
● Fast Execution (V8 Engine)
● Real-Time Data Handling
2. What is NPM?
NPM stands for the Node Package Manager. It is the package manager for
the NodeJS environment. It is used to install, share, and manage
dependencies (libraries, tools, or packages) in JavaScript applications.
Below are the following key points about the NPM:
● NPM uses a package.json file in NodeJS projects to track project
dependencies, versions, scripts, and metadata like the project's
name and version.
● NPM is accessed by a command-line interface (CLI). Common
commands include npm install to install packages, npm update to
update them, and npm uninstall to remove them.
3. Why is NodeJS single-threaded?
NodeJS 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 NodeJS to handle many concurrent requests
efficiently.
4. If NodeJS is single-threaded, then how does it handle
concurrency?
NodeJS is single-threaded, but it can handle concurrency efficiently
through its event-driven, non-blocking I/O model. While the event loop in
NodeJS runs on a single thread, it doesn’t block the execution of other
tasks when waiting for I/O operations, such as file reads or database
queries. Instead, NodeJS delegates these I/O tasks to the system's kernel,
allowing it to continue processing other requests. Once the I/O operation is
complete, the corresponding callback is added to a queue and processed
by the event loop. This non-blocking approach enables NodeJS to handle
multiple concurrent tasks without waiting for each one to finish
sequentially.
5. Why is NodeJS preferred over other backend technologies
like Java and PHP?
Here are some reasons why NodeJS is preferred:
● Fast Performance: NodeJS 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 NodeJS is based on
JavaScript, web developers can easily integrate it into their
projects.
6. What is the difference between Synchronous and
Asynchronous functions?
Here we have a difference table between Synchronous and Asynchronous
functions.
Synchronous Functions Asynchronous Functions
Blocks the execution until the Does not block the execution; allows
task completes. other tasks to proceed concurrently.
Executes tasks sequentially; Initiate tasks and proceed with other
each task must be completed operations while waiting for
before the next one starts. completion.
Typically returns a promise or callback
Returns the result immediately
or uses event handling to handle the
after completion.
result upon completion.
Error handling is more complex and
Errors can be easily caught with
often involves callbacks, promises, or
try-catch blocks.
async/await syntax.
Suitable for simple, sequential Ideal for I/O-bound operations,
tasks with predictable execution network requests, and tasks requiring
flow. parallel processing.
7. What are the module in NodeJS?
In a NodeJS Application, a Module can be considered as a block of code
that provides 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. They are useful because of their
reusability and ability to reduce the complexity of code into smaller pieces.
Examples of modules are. http, fs, os, path, etc.
8. What is the purpose of the 'require' keyword in NodeJS?
The require keyword in NodeJS is used to include and import modules
(external or built-in) into a NodeJS application.
Example
const http = require('http') //imports the HTTP module to
create a server.
9. What is middleware?
Middleware is the function that works between the request and the
response cycle. Middleware gets executed after the server receives the
request and before the controller sends the response.
10. How does NodeJS handle concurrency even after being
single-threaded?
NodeJS handles concurrency by using asynchronous, non-blocking
operations. Instead of waiting for one task to complete before starting the
next, it can initiate multiple tasks and continue processing while waiting
for them to finish, all within a single thread.
11. What is control flow in NodeJS?
Control flow in NodeJS refers to the sequence in which statements and
functions are executed. It manages the order of execution, handling
asynchronous operations, callbacks, and error handling to ensure smooth
program flow.
12. What do you mean by event loop in NodeJS?
The event loop in NodeJS 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.
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 NodeJS?
Here are some main disadvantages of NodeJS 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 NodeJS?
REPL in NodeJS 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 NodeJS?
We use the require module to import the External libraries in NodeJS. The
result returned by require() is stored in a variable, which is used to invoke
the functions using the dot notation.
17. What is the difference between NodeJS and Angular?
NodeJS Angular
Server-side runtime environment Front-end framework
TypeScript (primarily, but supports
JavaScript (or TypeScript)
JavaScript)
Runs on the server to handle Runs on the client side (browser) to
requests and responses. build user interfaces.
Performance-focused with
Highly efficient for I/O operations
optimization for large-scale
due to its non-blocking nature.
single-page applications.
Used for building interactive,
Primarily used for server-side dynamic, and responsive front-end
JavaScript execution and backend applications.
services.
18. What is package.json in NodeJS?
package.json in NodeJS 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 NodeJS?
You can create a simple HTTP server in NodeJS 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/');
});
20. What are the most commonly used libraries in NodeJS?
There are the two most commonly used libraries in NodeJs:
● 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 NodeJS, it helps in managing data relationships, schema
validation, and business logic.
21. What are promises in NodeJS?
A promise is an advancement of callbacks in NodeJS. In other words, a
promise is a JavaScript object that is used to handle all the asynchronous
data operations. While developing an application, you may encounter that
you are using a lot of nested callback functions, which causes a problem of
callback hell. Promises solve this problem of callback hell.\
22. How do you install, update, and delete a dependency?
● Install the Dependencies
NodeJS
● Update the Dependencies
NodeJS
● Delete the Dependencies
23. Which command used to import external libraries?
In NodeJS, 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');
NodeJS Interview Questions for Intermediate
In this set, we will be looking at intermediate Node Interview Questions
for candidates with over 2 years of experience.
24. What is event-driven programming in NodeJS?
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 NodeJS?
The Buffer class in NodeJS 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 NodeJS?
In NodeJS, 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 NodeJS.
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 NodeJS.
The Timers module in NodeJS 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 NodeJS 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 the callback after the Executes the callback immediately
current event loop cycl, but before after the current operation, before
the I/O tasks. any I/O or timers.
Executes after I/O events and before Executes before any I/O events or
timers. timers.
n cause a stack overflow if used
Less likely to cause a stack overflow excessively because it executes
because it is queued after the current before I/O or other operations,
event loop phase. potentially blocking the event
loop.
Used to schedule a callback to be
Used when you want to execute a executed before any I/O events or
callback after the event loop is done timers in the current phase.
processing the current phase but
before the next one starts.
setImmediate(() => { process.nextTick(() => {
console.log('Immediate'); }); console.log('Next Tick'); });
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 launch a new process Used specifically for spawning new
with a given command. NodeJS processes.
Returns a ChildProcess object
Returns a ChildProcess object with
that allows interaction with the
built-in support for IPC.
spawned process.
Built-in support for IPC, making it
No built-in support for IPC
easier to communicate between the
(requires additional setup).
parent and child processes.
Running external commands or Running NodeJS scripts in child
executing scripts (e.g., shell processes that can send and receive
scripts, commands). messages from the parent process.
spawn('ls', ['-lh', '/usr']) fork('child.js')
33. Explain the use of the passport module in NodeJS
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 NodeJS?
Fork is a method in NodeJS 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 NodeJS?
Body-parser is the NodeJS 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 NodeJS?
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 NodeJS application.
38. Explain the tls module in NodeJS..
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 NodeJS because NodeJS 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.
NodeJS 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 NodeJS, as it operates on the backend, outside the context of a web
page or browser.
40. How do you manage packages in your NodeJS project?
In a NodeJS project, package management is handled through npm (Node
Package Manager), which is the default package manager for NodeJS,
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 NodeJS is used to specify the
environment in which the NodeJS 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 NodeJS?
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.
NodeJS Interview Questions for Experienced
In this set, we will be covering Node interview question for experienced
developers with over 5 years of experience.
43. What is piping in NodeJS?
In NodeJS, 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 NodeJS.
44. What is a cluster in NodeJS?
Due to a single thread in NodeJS, 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 NodeJS
● 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 NodeJS?
Session management can be done in NodeJS 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
NodeJS?
Authentication is the process of verifying a user’s identity while
authorization is determining what actions can be performed. We use
packages like Passport and JWT to implement authentication and
authorization.
49. Explain the packages used for file uploading in NodeJS.the
The package used for file uploading in NodeJS 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 NodeJS middleware that is used for handling multipart/form-data,
which is a mostly used library for uploading files.
50. Explain the difference between NodeJS and server-side
scripting languages like Python
Server-Side Scripting Languages
NodeJS
(e.g., Python)
A runtime environment for A programming language that can be
executing JavaScript outside used for server-side scripting (e.g.,
the browser. Python, PHP, Ruby).
Built on JavaScript, primarily Built on Python, which is synchronous
used for asynchronous by default, but can also be used for
programming. asynchronous programming.
Thread-based concurrency
Non-blocking, event-driven I/O (multi-threading) or asynchronous
model using the Event Loop. programming with frameworks like
asyncio.
Highly performant for
I/O-heavy tasks but less More suitable for CPU-heavy operations
efficient for CPU-heavy but can be less performant in handling
operations due to high concurrency compared to NodeJS.
single-threaded nature.
Commonly used for general-purpose
Used for building fast, scalable, programming, web development, and
I/O-bound applications (e.g., CPU-bound tasks (e.g., Django for web,
APIs, real-time apps). machine learning with libraries like
TensorFlow).
51. How to Connect NodeJS 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 NodeJS?
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 NodeJS 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 NodeJS developers as it
reduces the cache size which makes the application more efficient.
However, it is very easy to integrate Redis with NodeJS 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 NodeJS
The Util module in NodeJS provides access to various utility functions.
There are various utility modules available in the NodeJS module library.
● OS Module: Operating System-based utility modules for NodeJS
are provided by the OS module.
● Path Module: The path module in NodeJS 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 NodeJS is used for the creation of
both client and server. Similar to DNS Module this module also
provides an asynchronous network wrapper.
56. How to handle environment variables in NodeJS?
We use process.env to handle environment variables in NodeJS. 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
57. Explain DNS module in NodeJS
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.
58. What is the difference between setImmediate() and
setTimeout()?
steImmediate() setTimeout()
Executes the callback
Executes the callback after the
immediately after the current
specified delay (in ms).
event loop phase.
Adds the callback to the next Adds the callback to the timer queue,
iteration of the event loop, in the to be executed after the specified
check phase. delay.
Executes only after the specified delay,
Has no timer; it is designed for
which may vary slightly based on
immediate execution.
system timing resolution.
No delay, always executes after Executes after the specified delay
the current phase finishes. (minimum of 1 ms).
Used for callbacks that need to
Used for delaying the execution of a
run immediately after I/O events
callback by a specific time.
or timers.
59. For NodeJS, why does Google use the V8 engine?
Google for the V8 engine for NodeJS of the following reasons mentioned
below:
● High Performance: V8 is a highly optimized JavaScript engine
designed for speed. It compiles JavaScript directly into machine
code, which makes it much faster than interpreted JavaScript.
● Just-In-Time (JIT) Compilation: V8 uses JIT compilation, which
translates JavaScript code into machine code during execution,
enabling faster execution compared to traditional interpretation.
● Cross-platform Compatibility: V8 is cross-platform due to which
the NodeJS application can run on that platforms.
● Integration with Google Chrome: The Google Chrome by using
the V8 engine in the NodeJS ensures consistency in performance
and features.
● Asynchronous I/O Efficiency: The V8 engine can handle the
non-blocking, asynchronous I/O operations which is important for
handling the multiple tasks in NodeJS.
60. What is an Event Emitter in Node.js?
In Node.js, an Event Emitteris 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.
Key Concepts of EventEmitter:
● Emitting Events: Objects can emit custom events by calling the
.emit() method. This triggers all listeners that are registered for
that event.
● Listening to Events: You can listen for specific events using the
.on() or .once() methods. .on() will listen for the event
indefinitely, while .once() will listen for the event only once.
● Event Handling: Event listeners (callbacks) are executed when
the corresponding event is emitted. These listeners are often
used to handle asynchronous operations like HTTP requests or
file I/O.
●