Introduction
Node.js is a popular JavaScript runtime used to build REST APIs, web applications, real-time systems, and backend services. During Node.js interviews, candidates are often asked to solve coding problems that test their JavaScript fundamentals, asynchronous programming skills, data handling, error management, and ability to build backend functionality.
Practicing coding questions helps developers understand how to apply Node.js concepts to real-world problems rather than simply memorizing definitions.
In this tutorial, we will cover important Node.js coding interview questions with solutions, explanations, and expected outputs. These examples are useful for freshers, intermediate developers, and experienced professionals preparing for backend developer interviews.
1. How Do You Create a Simple HTTP Server in Node.js?
The built-in http module allows you to create an HTTP server without installing an external framework.
Example
const http = require("node:http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("Welcome to Node.js!");
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Output
When you run the program, the console displays:
Open http://localhost:3000 in a browser to see:
Welcome to Node.js!
Explanation
The createServer() method creates an HTTP server and registers a request handler. The handler sends an HTTP status code and a text response. The listen() method starts the server on port 3000.
Interview tip: Be prepared to explain the difference between the built-in HTTP module and the Express.js framework.
2. How Do You Read a File Asynchronously in Node.js?
Node.js provides the fs module for file-system operations. Its Promise-based API allows developers to read files without synchronously blocking the JavaScript thread.
Example
const fs = require("node:fs/promises");
async function readFile() {
try {
const data = await fs.readFile("sample.txt", "utf8");
console.log(data);
} catch (error) {
console.error("Error reading file:", error.message);
}
}
readFile();
Expected Output
If sample.txt contains:
The output is:
Explanation
The readFile() method returns a Promise. The await keyword waits for that Promise to settle inside the asynchronous function. The try…catch block handles errors such as a missing file or insufficient permissions.
3. How Do You Create and Use a Custom Module in Node.js?
Node.js allows developers to divide an application into reusable modules.
Example
Create a file named math.js:
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = {
add,
multiply
};
Create another file named app.js:
const math = require("./math");
console.log(math.add(10, 20));
console.log(math.multiply(5, 4));
Output
20
Explanation
The module.exports object exposes functions from math.js. The require() function loads the exported module into app.js.
This example uses CommonJS modules. Node.js also supports ECMAScript modules using import and export.
4. How Do You Reverse a String in Node.js?
String manipulation is a common coding interview topic.
Example
function reverseString(str) {
return Array.from(str).reverse().join("");
}
console.log(reverseString("Node.js"));
Output
Explanation
Array.from() converts the string into an array of Unicode code points. The reverse() method reverses the array, and join(“”) combines the elements into a string.
This approach is suitable for many basic examples, although reversing complex Unicode text correctly may require handling grapheme clusters.
5. How Do You Check Whether a String Is a Palindrome?
A palindrome reads the same forward and backward under a chosen comparison rule.
Example
function isPalindrome(str) {
const normalized = str
.toLowerCase()
.replace(/[^a-z0-9]/g, "");
return normalized ===
Array.from(normalized).reverse().join("");
}
console.log(isPalindrome("Madam"));
console.log(isPalindrome("Node.js"));
console.log(isPalindrome("A man, a plan, a canal: Panama"));
Output
false
true
Explanation
The function converts the string to lowercase and removes non-alphanumeric characters before comparing it with its reverse. This makes the comparison case-insensitive and ignores spaces and punctuation.
6. How Do You Find Duplicate Elements in an Array?
Finding duplicate values is a common problem in JavaScript and Node.js interviews.
Example
function findDuplicates(arr) {
const seen = new Set();
const duplicates = new Set();
for (const item of arr) {
if (seen.has(item)) {
duplicates.add(item);
} else {
seen.add(item);
}
}
return [...duplicates];
}
console.log(findDuplicates([1, 2, 3, 2, 4, 1, 5]));
Output
Explanation
The seen set tracks values that have already appeared. When a value appears again, it is added to the duplicates set.
Both sets preserve insertion order, so the result contains each duplicated value once, ordered by its second occurrence.
Time complexity: O(n) on average, where n is the number of array elements.
7. How Do You Remove Duplicate Elements from an Array?
A Set stores unique values and can be used to remove duplicates.
Example
function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 3, 5]));
Output
[1, 2, 3, 4, 5]
Explanation
The Set removes repeated values, and the spread operator converts the resulting set back into an array. The original order of the first occurrence of each value is preserved.
8. How Do You Find the Largest Number in an Array?
Example
function findLargest(arr) {
if (arr.length === 0) {
throw new Error("Array cannot be empty");
}
let largest = arr[0];
for (const num of arr) {
if (num > largest) {
largest = num;
}
}
return largest;
}
console.log(findLargest([12, 45, 7, 89, 23]));
Output
Explanation
The function starts with the first element as the largest value. It compares each remaining element with the current largest value and updates it whenever a larger number is found.
Time complexity: O(n).
The empty-array check prevents the function from returning an invalid result when no elements are provided.
9. How Do You Count the Frequency of Each Character in a String?
Example
function characterFrequency(str) {
const frequency = {};
for (const char of str) {
frequency[char] = (frequency[char] || 0) + 1;
}
return frequency;
}
console.log(characterFrequency("node"));
Output
Explanation
The function loops through each character and increases its count in an object.
For production code handling arbitrary user-controlled strings, consider using a Map or a null-prototype object to avoid special object-property names affecting the result.
10. How Do You Find the First Non-Repeating Character in a String?
Example
function firstNonRepeatingChar(str) {
const frequency = new Map();
for (const char of str) {
frequency.set(
char,
(frequency.get(char) || 0) + 1
);
}
for (const char of str) {
if (frequency.get(char) === 1) {
return char;
}
}
return null;
}
console.log(firstNonRepeatingChar("aabbcde"));
console.log(firstNonRepeatingChar("aabb"));
Output
null
Explanation
The first loop counts the occurrences of every character. The second loop returns the first character whose frequency is one.
The function returns null when every character appears more than once.
11. How Do You Sort an Array of Objects by a Property?
Sorting arrays of objects is useful when working with API responses, product lists, and database results.
Example
const users = [
{ name: "Rahul", age: 28 },
{ name: "Amit", age: 22 },
{ name: "Priya", age: 25 }
];
const sortedUsers = [...users].sort(
(a, b) => a.age - b.age
);
console.log(sortedUsers);
Output
{ name: “Amit”, age: 22 },
{ name: “Priya”, age: 25 },
{ name: “Rahul”, age: 28 }
]
Explanation
The comparison function sorts users by ascending age. The spread operator creates a shallow copy so the original array is not directly sorted.
12. How Do You Implement a Promise in Node.js?
A Promise represents the eventual completion or failure of an asynchronous operation.
Example
function getUser() {
return new Promise((resolve, reject) => {
const user = {
id: 1,
name: "Rahul"
};
if (user) {
resolve(user);
} else {
reject(new Error("User not found"));
}
});
}
getUser()
.then((user) => {
console.log(user);
})
.catch((error) => {
console.error(error.message);
});
Output
Explanation
The resolve() function fulfills the Promise, while reject() rejects it. The then() method handles fulfillment, and catch() handles rejection.
In a real application, a Promise commonly represents an operation such as reading a file, querying a database, or making a network request.
13. How Do You Execute Multiple Asynchronous Operations in Parallel?
When independent operations do not depend on each other’s results, Promise.all() can execute them concurrently.
Example
function getUser() {
return new Promise((resolve) => {
setTimeout(() => resolve("User loaded"), 1000);
});
}
function getProducts() {
return new Promise((resolve) => {
setTimeout(() => resolve("Products loaded"), 1000);
});
}
async function loadData() {
const [user, products] = await Promise.all([
getUser(),
getProducts()
]);
console.log(user);
console.log(products);
}
loadData();
Output
Products loaded
Both operations start before the program awaits their results. They can therefore complete in approximately one second rather than approximately two seconds when each takes one second and is awaited sequentially.
Actual elapsed time depends on runtime scheduling and workload.
14. How Do You Create a Simple REST API Using Express.js?
Express.js is a popular framework for building HTTP APIs in Node.js.
First, install Express:
npm install express
Example
const express = require("express");
const app = express();
app.use(express.json());
const users = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" }
];
app.get("/users", (req, res) => {
res.json(users);
});
app.get("/users/:id", (req, res) => {
const user = users.find(
(item) => item.id === Number(req.params.id)
);
if (!user) {
return res.status(404).json({
message: "User not found"
});
}
res.json(user);
});
app.listen(3000, () => {
console.log("API running on port 3000");
});
Example requests
Get all users:
GET http://localhost:3000/users
Get a specific user:
GET http://localhost:3000/users/1
Expected response
{
"id": 1,
"name": "Rahul"
}
Explanation
The application defines two GET routes. The first returns all users, while the second finds a user by ID. If the user does not exist, the server returns a 404 status.
This example uses an in-memory array. A real API should generally retrieve data from a database and validate incoming input appropriately.
15. How Do You Create a Middleware Function in Express.js?
Middleware functions can execute code before a route handler sends a response.
Example
function checkApiKey(req, res, next) {
const apiKey = req.headers["x-api-key"];
if (apiKey !== process.env.API_KEY) {
return res.status(401).json({
message: "Unauthorized"
});
}
next();
}
app.get("/protected", checkApiKey, (req, res) => {
res.json({
message: "Access granted"
});
});
Explanation
The middleware checks the request’s API key against a configured environment variable. If the key is invalid, it returns an HTTP 401 response. Otherwise, next() passes control to the route handler.
This is a simplified example. Production authentication should use an appropriate credential-management strategy, and secrets must not be hard-coded or committed to source control.
16. How Do You Handle Errors in an Express.js Application?
Centralized error-handling middleware makes it easier to manage application errors consistently.
Example
app.get("/example", (req, res, next) => {
try {
throw new Error("Something went wrong");
} catch (error) {
next(error);
}
});
app.use((err, req, res, next) => {
console.error(err);
if (res.headersSent) {
return next(err);
}
res.status(500).json({
message: "Internal server error"
});
});
Explanation
Calling next(error) passes the error to Express error-handling middleware. The centralized handler logs the error and sends a generic response to the client.
This prevents internal implementation details from being exposed through error responses.
For asynchronous route handlers, ensure rejected Promises are forwarded to error-handling middleware. The exact behavior depends on the Express version and the way the handler is implemented.
17. How Do You Copy a File Using Streams in Node.js?
Streams are useful for copying large files without loading the entire file into memory.
Example
const fs = require("node:fs");
const { pipeline } = require("node:stream");
pipeline(
fs.createReadStream("source.txt"),
fs.createWriteStream("destination.txt"),
(error) => {
if (error) {
console.error("Copy failed:", error.message);
return;
}
console.log("File copied successfully");
}
);
Output
Explanation
The readable stream reads data in chunks, and the writable stream writes those chunks to the destination. The pipeline() function manages data flow and propagates stream errors.
18. How Do You Implement a Simple Cache in Node.js?
A cache stores frequently requested values so that they can be retrieved without repeating an expensive operation.
Example
const cache = new Map();
function getCachedValue(key, fetchValue) {
if (cache.has(key)) {
return Promise.resolve(cache.get(key));
}
return Promise.resolve()
.then(fetchValue)
.then((value) => {
cache.set(key, value);
return value;
});
}
async function main() {
const result = await getCachedValue(
"user:1",
async () => ({ id: 1, name: "Rahul" })
);
console.log(result);
}
main();
Output
Explanation
The function checks whether the requested key exists in the cache. If it does, the stored value is returned. Otherwise, it calls the supplied function and stores the result.
This basic implementation has no expiration, size limit, or protection against duplicate concurrent fetches. A production cache should account for memory usage, invalidation, stale data, and concurrent requests.
19. How Do You Implement a Basic Rate Limiter in Express.js?
Rate limiting restricts how frequently a client can make requests within a defined period.
One practical approach is to use a maintained middleware package.
Install it with:
npm install express-rate-limit
Example
const rateLimit = require("express-rate-limit");
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 100,
standardHeaders: "draft-8",
legacyHeaders: false,
message: {
message: "Too many requests. Try again later."
}
});
app.use("/api", apiLimiter);
Explanation
This configuration limits clients to 100 requests per 15-minute window for routes under /api, subject to the middleware’s configured key-generation and storage behavior.
For applications running across multiple servers, use a shared store when consistent limits across instances are required. Also configure trusted proxy handling carefully so that client IP addresses cannot be spoofed through forwarded headers.
20. How Do You Run a CPU-Intensive Task Using Worker Threads?
Worker threads allow CPU-intensive JavaScript to execute outside the main JavaScript thread.
Create a file named worker.js:
const { parentPort } = require("node:worker_threads");
let total = 0;
for (let i = 1; i <= 1000000; i++) {
total += i;
}
parentPort.postMessage(total);
Create app.js:
const { Worker } = require("node:worker_threads");
const worker = new Worker("./worker.js");
worker.on("message", (result) => {
console.log("Total:", result);
});
worker.on("error", console.error);
worker.on("exit", (code) => {
if (code !== 0) {
console.error(`Worker stopped with exit code ${code}`);
}
});
Output
Explanation
The worker performs the calculation and sends the result to the main thread. This allows the main thread to remain available for other JavaScript work while the calculation runs.
For production applications, consider worker lifecycle management, error handling, and a worker pool rather than creating a new worker for every small task.
Additional Node.js Coding Questions for Practice
The following questions are useful for additional interview preparation:
- Write a function to find the second-largest number in an array.
- Implement a function to flatten a nested array.
- Write a program to check whether two strings are anagrams.
- Implement a debounce function in JavaScript.
- Implement a throttle function.
- Write a function to group an array of objects by a property.
- Implement a retry mechanism for a failed asynchronous operation.
- Write a function to process an array of items with a concurrency limit.
- Implement pagination for a REST API.
- Write a program to merge two objects safely.
- Implement a timeout wrapper for a Promise.
- Write a function to validate an email address.
- Implement a basic queue using JavaScript.
- Write a function to find the most frequent element in an array.
- Implement a graceful shutdown handler for a Node.js server.
These exercises cover JavaScript fundamentals, asynchronous programming, data processing, and backend development patterns commonly encountered in interviews.
Common Mistakes to Avoid in Node.js Coding Interviews
Candidates should watch out for the following mistakes:
- Forgetting to handle rejected Promises.
- Using synchronous file operations unnecessarily in request handlers.
- Ignoring edge cases such as empty arrays and missing values.
- Mutating input arrays when the original data should remain unchanged.
- Blocking the event loop with long-running calculations.
- Failing to validate API input.
- Returning inappropriate HTTP status codes.
- Ignoring stream errors and backpressure.
- Building caches without expiration or size limits.
- Writing code without considering time and space complexity.
Conclusion
Node.js coding interviews test practical programming ability, JavaScript fundamentals, asynchronous execution, file handling, API development, and problem-solving skills.
Start by practicing string and array problems, then move to Promises, Express.js APIs, streams, caching, rate limiting, and worker threads. For each solution, understand why it works, test edge cases, and explain its time and space complexity when relevant.
Consistent practice with these Node.js coding interview questions will help you write cleaner backend code and prepare for interviews at different experience levels.