Node JS
Interview Questions with Answers

Explore Our Courses
1. What is Node.js, and why is it popular for backend development?
Node.js is a runtime environment that allows JavaScript to run outside the browser, mainly on the server side. It uses Google’s V8 JavaScript engine (the same engine that powers Chrome) to execute code very fast.
It is popular for backend development because:
- It handles many connections at once using its non-blocking, event-driven model.
- Developers can use JavaScript on both frontend and backend, making development faster.
- It has a huge npm ecosystem with thousands of ready-made packages.
- It is excellent for real-time applications like chat apps, online games, and live tracking.
Example: WhatsApp uses Node.js to handle millions of simultaneous connections in real time.
Boost your career with Node.js mastery—start learning today!
2. Who created Node.js, and what language is it built on?
Node.js was created in 2009 by Ryan Dahl.
It is built primarily on:
- C++ (for the core engine and performance optimization),
- JavaScript (for writing applications),
- libuv (C library) for handling asynchronous I/O operations.
Example: Ryan Dahl built Node.js to fix the problem of blocking I/O in web servers like Apache.
3. What is the difference between Node.js and JavaScript in the browser?
- In the browser, JavaScript is mainly used for user interfaces, DOM manipulation, and client-side logic. It runs inside a restricted environment with no direct access to the file system.
- In Node.js, JavaScript runs on the server, where it can read/write files, handle databases, manage APIs, and perform backend logic.
Example:
- Browser JavaScript: Updating a webpage when a button is clicked.
- Node.js JavaScript: Handling a login request by verifying user credentials in a database.
4. Why is Node.js considered cross-platform?
Node.js is considered cross-platform because it runs on multiple operating systems like Windows, macOS, and Linux without modification. The same Node.js code can be executed across these platforms because it is based on portable C++ code, libuv, and the V8 engine.
Example:
If you write a Node.js app for a chat server, you can run it on both Linux servers and Windows servers without rewriting the code.
5. What is the role of npm in Node.js?
npm (Node Package Manager) is the default package manager for Node.js. It helps developers:
- Install third-party libraries or frameworks,
- Manage project dependencies,
- Share their own packages with others.
It is the world’s largest software registry, containing millions of open-source packages.
Example:
To install Express.js (a popular Node.js framework), we run:
npm install express
6. What is non-blocking I/O in Node.js?
Non-blocking I/O means that Node.js does not wait for one task (like reading a file or querying a database) to finish before moving to the next task. Instead, it registers a callback or promise to handle the result once it’s ready. This allows Node.js to handle thousands of operations concurrently.
Example:
If Node.js reads a file, it immediately moves to serve another request instead of waiting for the file to finish loading.
7. How does Node.js handle asynchronous operations by default?
Node.js handles asynchronous operations using the event loop and callback functions (or Promises/async-await in modern code).
When an async operation starts, Node.js registers it and continues executing other code. Once the operation finishes, its callback is pushed to the event loop queue, and executed when the call stack is free.
Example:
console.log("Start");
setTimeout(() => console.log("Async Task Done"), 2000);
console.log("End");
Output:
Start
End
Async Task Done
8. What is the difference between synchronous and asynchronous code in Node.js?
- Synchronous code: Runs one operation at a time. The program waits for a task to finish before moving to the next. This can block the execution.
- Asynchronous code: Tasks are executed in parallel without waiting. Node.js continues running other code and handles results later via callbacks, promises, or async/await.
Example:
- Sync: Reading a file line by line (next code waits).
- Async: Reading a file while serving other users at the same time.
9. Why is Node.js well-suited for real-time applications?
Real-time apps need instant data exchange between client and server. Node.js is perfect because:
- It uses WebSockets for two-way communication.
- Its event-driven architecture handles many concurrent connections efficiently.
- Non-blocking I/O ensures that data is processed instantly without delay.
Example:
Chat applications, stock price dashboards, live tracking apps, and multiplayer games often use Node.js.
10. What is the difference between Node.js and traditional multi-threaded servers?
- Traditional servers (like Java, PHP, Apache) use a multi-threaded model where each request gets a separate thread. This consumes more memory and is less efficient with thousands of requests.
- Node.js uses a single-threaded event loop with non-blocking I/O, allowing it to handle many requests with minimal resources.
Example:
- Apache server: If 10,000 people connect, it creates 10,000 threads, which may slow down.
- Node.js server: Handles 10,000 connections with one event loop efficiently.
11. What are built-in (core) modules in Node.js?
Built-in (or core) modules are the pre-installed modules that come with Node.js. You don’t need to install them separately using npm. They provide essential functionalities for building applications.
Some popular core modules are:
- fs (file system) → for file operations
- http → for creating web servers
- path → for handling file paths
- os → for system-related information
- events → for event handling
Example:
const os = require('os');
console.log(os.platform()); // prints current operating system
12. How do you import a module in Node.js?
In Node.js, you use the require() function or ES6 import syntax to import a module.
Example using require:
const fs = require('fs');
Example using import (ES6):
import fs from 'fs';
13. What is the difference between require() and import?
- require():
- CommonJS syntax (older standard in Node.js).
- Can be used anywhere in the code.
- Returns an object immediately.
- import:
- ES6 (modern JavaScript) syntax.
- Must be declared at the top of the file.
- Supports static analysis and tree-shaking.
Example:
// CommonJS
const http = require('http');
// ES6
import http from 'http';
14. What are third-party modules in Node.js?
Third-party modules are packages created by other developers and published on npm. You install them to extend your project with additional features.
Example:
- express → Web framework
- mongoose → MongoDB object modeling
- lodash → Utility functions
To install a module:
npm install express
Then use it:
const express = require('express');
const app = express();
15. How do you create your own module in Node.js?
You can create your own module by writing functions or variables in one file and then exporting them. Another file can then import and use them.
Example:
File: math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
File: app.js
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8
16. How do you read a file synchronously in Node.js?
You use fs.readFileSync(), which blocks the code until the file is completely read.
Example:
const fs = require('fs');
const data = fs.readFileSync('file.txt', 'utf8');
console.log(data);
17. How do you read a file asynchronously in Node.js?
You use fs.readFile(), which does not block the code. It reads the file in the background and uses a callback once done.
Example:
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
18. How do you write data to a file in Node.js?
You can use either fs.writeFile() (async) or fs.writeFileSync() (sync).
Example (async):
const fs = require('fs');
fs.writeFile('output.txt', 'Hello Node.js!', (err) => {
if (err) throw err;
console.log('File written successfully');
});
19. How do you check if a file exists in Node.js?
You can use fs.existsSync() (sync) or fs.access() (async).
Example (sync):
const fs = require('fs');
if (fs.existsSync('file.txt')) {
console.log('File exists');
} else {
console.log('File does not exist');
}
20. How do you delete a file in Node.js?
You can use fs.unlink() (async) or fs.unlinkSync() (sync).
Example (async):
const fs = require('fs');
fs.unlink('file.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully');
});
Get interview-ready and secure your dream Node.js job now!
21. How do you create a simple HTTP server in Node.js?
You can create an HTTP server using the built-in http module. The createServer() method handles incoming requests and responses.
Example:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Node.js Server!');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
22. How do you send an HTTP response in Node.js?
You use the response object (res) methods like writeHead() to set headers and end() to send the response body.
Example:
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Welcome to My Server</h1>');
}).listen(4000);
23. How do you handle query parameters in a Node.js HTTP server?
You use the built-in url module to parse the request URL and extract query parameters.
Example:
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Hello ${query.name || 'Guest'}`);
}).listen(5000);
**If you visit http://localhost:5000/?name=Neha, it will respond with:
Hello Neha
24. How do you handle POST requests in Node.js?
POST data comes in chunks, so you must collect it using the request’s data and end events.
Example:
const http = require('http');
http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Data received: ${body}`);
});
}
}).listen(6000);
25. What’s the difference between http and https modules in Node.js?
- http module: Used for creating servers that run on the HTTP protocol. It’s unencrypted and not secure.
- https module: Used for creating servers that run on the HTTPS protocol. It uses SSL/TLS certificates for encrypted communication.
Example use case:
- Use http for local testing or internal apps.
- Use https for production apps where security matters, like online banking or e-commerce.
26. What is the EventEmitter class in Node.js?
The EventEmitter class (from the built-in events module) allows objects to emit events and register listeners for those events. It’s the foundation of Node.js’s event-driven architecture.
Example:
const EventEmitter = require('events');
const emitter = new EventEmitter();
27. How do you register an event listener in Node.js?
You use the ‘on()’ method of EventEmitter to register a listener for a specific event.
Example:
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', (name) => {
console.log(`Hello, ${name}`);
});
emitter.emit('greet', 'Neha');
Output:
Hello, Neha
28. How do you trigger an event in Node.js?
You trigger (emit) an event using the emit() method of EventEmitter.
Example:
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('message', () => console.log('Message event triggered'));
emitter.emit('message');
Output:
Message event triggered
29. What is the difference between on and once in EventEmitter?
- on: Registers a listener that runs every time the event is emitted.
- once: Registers a listener that runs only the first time, then removes itself automatically.
Example:
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.once('start', () => console.log('This runs only once'));
emitter.on('start', () => console.log('This runs every time'));
emitter.emit('start');
emitter.emit('start');
Output:
This runs only once
This runs every time
This runs every time
30. Can you remove an event listener in Node.js? If yes, how?
Yes, you can remove an event listener using removeListener() or off() (modern syntax).
Example:
const EventEmitter = require('events');
const emitter = new EventEmitter();
function greet(name) {
console.log(`Hello, ${name}`);
}
emitter.on('greet', greet);
emitter.emit('greet', 'Neha'); // Works
emitter.off('greet', greet); // Remove listener
emitter.emit('greet', 'Tushar'); // Nothing happens
31. How do you initialize a Node.js project with npm?
To initialize a Node.js project, we use the command:
npm init
It asks questions like project name, version, description, etc., and then creates a package.json file.
If you want to skip all questions and create a default setup:
npm init -y
Example:
Ramesh is starting a project for his “Online Library” system. He runs npm init -y and gets a package.json file instantly.
32. What is the difference between dependencies and devDependencies?
- dependencies: These are packages required for the project to run in production.
- devDependencies: These are packages needed only during development, not in production.
Example:
- Seema is building a shopping app. She installs Express.js for the server, so it goes into dependencies.
- She also installs Jest for testing, so it goes into devDependencies.
33. How do you install a specific version of a package with npm?
You can install a specific version using @version.
Example:
npm install express@4.18.2
This installs Express.js version 4.18.2.
Imagine Ankit is working in a team where everyone uses Express v4.18.2 for consistency. He installs the same version using the above command.
34. What is the purpose of the package.json file?
The package.json file is the heart of a Node.js project. It:
- Stores project metadata (name, version, author).
- Defines dependencies and devDependencies.
- Allows scripts (like npm start).
- Helps others set up the project easily.
Example:
Priya shares her project with a friend. Instead of sending all installed libraries, she just shares package.json. Her friend runs npm install and gets everything automatically.
35. What is the difference between npm install and npm ci?
- npm install: Installs dependencies from package.json. If package-lock.json exists, it updates it if needed.
- npm ci: Installs dependencies strictly from package-lock.json. It’s faster and ensures exact versions.
Example:
- When Rahul is developing and may add new packages, he uses npm install.
- When his team deploys the app on a server, they use npm ci to get the exact same versions without changes.
36. What is Express.js, and why is it used with Node.js?
Express.js is a lightweight web framework for Node.js. It simplifies handling routes, requests, and responses.
It is used because:
- It reduces the boilerplate code of raw http module.
- It provides middleware support.
- It makes building APIs and web apps faster.
Example:
If Neha wants to build an API for her food delivery app, Express.js helps her manage routes like /menu, /orders, /cart very easily.
37. How do you install Express.js?
You install Express.js using npm:
npm install express
Example:
Amit is starting a “Student Management System” project. He runs npm install express to add Express.js to his project.
38. How do you create a simple route in Express.js?
You first import Express, create an app, and then define a route with app.get().
Example:
const express = require('express');
const app = express();
app.get('/hello', (req, res) => {
res.send('Hello from Learn2Earn Labs!');
});
app.listen(3000, () => console.log('Server running on port 3000'));
**When Sunita visits http://localhost:3000/hello, she sees:
Hello from Learn2Earn Labs!
39. How do you send a JSON response in Express.js?
You use the res.json() method.
Example:
const express = require('express');
const app = express();
app.get('/student', (req, res) => {
res.json({ name: 'Arjun', course: 'Full Stack Development' });
});
app.listen(4000);
Visiting /student gives:
{ "name": "Arjun", "course": "Full Stack Development" }
40. What is middleware in Express.js?
Middleware is a function that runs between the request and the response. It can modify requests, add logic, or stop requests before reaching the final route handler.
Types:
- Application-level middleware (applies to all routes).
- Router-level middleware (applies to specific routes).
- Built-in middleware like express.json().
Example:
const express = require('express');
const app = express();
// Middleware for logging
app.use((req, res, next) => {
console.log(`Request from: ${req.url}`);
next();
});
app.get('/', (req, res) => res.send('Welcome Rajesh!'));
app.listen(5000);
Here, whenever Rajesh visits any route, the middleware logs the URL before sending the response.
Level up your skills and crack Node.js interviews with ease!
41. How do you connect Node.js to a MongoDB database?
You use the official MongoDB Node.js driver or Mongoose (an ODM).
Example (with Mongoose):
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/school')
.then(() => console.log('MongoDB connected successfully'))
.catch(err => console.error('Connection error:', err));
Here, Pooja is building a “Student Records System,” and she connects her Node.js app to a MongoDB database named school.
42. How do you connect Node.js to a MySQL database?
You install the mysql2 package and use it to create a connection.
Example:
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '12345',
database: 'student'
});
connection.connect(err => {
if (err) throw err;
console.log('MySQL connected successfully');
});
Here, Ravi connects his Node.js project to a MySQL database called student.
43. What is the difference between callback-based and promise-based database queries?
- Callback-based: You pass a function that runs when the query finishes.
- Promise-based: You use .then() and .catch() or async/await for cleaner code.
Example (MySQL):
- Callback style:
connection.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
});
- Promise style (with mysql2/promise):
const mysql = require('mysql2/promise');
async function fetchUsers() {
const connection = await mysql.createConnection({ host: 'localhost', user: 'root', database: 'student' });
const [rows] = await connection.execute('SELECT * FROM users');
console.log(rows);
}
fetchUsers();
44. How do you handle database errors in Node.js?
- Always check for error objects in callbacks or promises.
- Use try/catch with async/await.
- Log errors and return friendly messages to users.
Example:
connection.query('SELECT * FROM users', (err, results) => {
if (err) {
console.error('Database error:', err.message);
return;
}
console.log(results);
});
If Sneha mistypes a query, the error is caught and logged instead of crashing the app.
45. What’s the role of an ORM in Node.js applications?
An ORM (Object-Relational Mapping) helps developers interact with databases using objects instead of writing raw SQL queries.
Benefits:
- Simplifies database operations.
- Makes code more readable.
- Provides validation and schema management.
Example:
Arjun uses Sequelize ORM for MySQL. Instead of writing SQL, he just does:
User.create({ name: ‘Arjun’, email: ‘arjun@learntoearnlabs.com’ });
46. How do you handle errors in Node.js using callbacks?
In callbacks, the first parameter is usually the error object. You check it before handling the result.
Example:
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err.message);
return;
}
console.log(data);
});
If Ramesh tries to read a missing file, the error is caught in the callback.
47. How do you handle errors using try/catch with async/await?
When using async/await, you wrap the code in a try/catch block to catch errors.
Example:
async function getData() {
try {
const data = await fs.promises.readFile('data.txt', 'utf8');
console.log(data);
} catch (err) {
console.error('Error occurred:', err.message);
}
}
getData();
If Priya’s file is missing, the error is caught by catch.
48. What is the role of throw in Node.js error handling?
The throw keyword is used to manually raise an error. It stops execution and passes control to the nearest error handler.
Example:
function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero is not allowed');
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (err) {
console.error(err.message);
}
If Suresh tries to divide by zero, the function throws an error, and it’s caught in catch.
49. What is the difference between operational errors and programmer errors?
- Operational errors: Expected problems caused by external factors (e.g., database down, file not found, network issue).
- Programmer errors: Mistakes in the code (e.g., using an undefined variable, wrong function call).
Example:
- If Anjali’s server can’t connect to the database → operational error.
- If Anjali forgets to define a variable before using it → programmer error.
50. How do you prevent your Node.js app from crashing on runtime errors?
- Always handle errors using try/catch or error callbacks.
- Use global error handlers like process.on(‘uncaughtException’) and process.on(‘unhandledRejection’).
- Validate inputs to avoid unexpected errors.
- Use monitoring tools like PM2 or Winston for logging.
Example:
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err.message);
});
process.on('unhandledRejection', (reason) => {
console.error('Unhandled Rejection:', reason);
});
If Manoj’s app faces an unexpected error, it logs it instead of crashing.
51. What is the purpose of the global object in Node.js?
The global object in Node.js is like the window object in browsers. It provides variables, functions, and objects that are available everywhere without requiring an import.
Examples of properties inside global:
- setTimeout
- console
- process
Example:
console.log(global.setTimeout === setTimeout); // true
This shows that setTimeout is part of the global object.
52. How is console.log implemented in Node.js?
console.log is a wrapper around process.stdout.write(), which writes directly to the terminal. Node.js formats the message before sending it to the standard output.
Example:
console.log("Hello");
process.stdout.write("Hello\n");
Both lines output the same thing to the terminal.
53. What are environment variables in Node.js, and how do you use them?
Environment variables are key-value pairs stored outside your code, usually in the system or .env file. They are used for configuration (like database URLs, API keys, ports).
In Node.js, you access them using process.env.
Example:
// .env file
PORT=4000
// app.js
console.log(process.env.PORT); // 4000
This allows developers like Rajesh to keep sensitive data out of the code.
54. What is the difference between relative and absolute paths in Node.js?
- Relative path: Starts from the current working directory (e.g., ./data/file.txt).
- Absolute path: Starts from the root of the file system or project (e.g., /Users/Ravi/project/data/file.txt).
Example:
const path = require('path');
console.log(path.resolve('data.txt')); // Converts relative path into absolute
55. What are streams in Node.js, at a high level?
Streams are a way to read or write data piece by piece instead of loading everything into memory at once. They are efficient for handling large files or data transfer.
Types of streams:
- Readable (data comes in chunks)
- Writable (data is written in chunks)
- Duplex (both read and write, like sockets)
- Transform (modify data while streaming)
Example:
Reading a big movie file using streams saves memory compared to loading the entire file.
56. What is REPL in Node.js, and how do you use it?
REPL stands for Read, Eval, Print, Loop. It is an interactive shell where you can run JavaScript code directly.
To use it, just type:
node
Then you can try:
> 5 + 5
10
It’s useful for testing small code snippets quickly.
57. How do you check the Node.js version installed on your machine?
Run the following command in the terminal:
node -v
or
node --version
Example output:
v20.11.1
58. What is the difference between LTS and Current versions of Node.js?
- LTS (Long Term Support): Stable version recommended for most developers. Gets security and bug fixes for a long time.
- Current: Latest features and updates, but may not be as stable.
Example:
If Anjali is working on a production banking system, she should use LTS. If she is experimenting with new features, she can try the Current version.
59. How do you uninstall a global npm package?
You use the npm uninstall -g command.
Example:
npm uninstall -g nodemon
This removes nodemon from the global packages.
60. What are some common use cases of Node.js?
Node.js is versatile and widely used for:
- Web servers & APIs (Express.js apps, REST APIs)
- Real-time apps (chat apps, live tracking, multiplayer games)
- File operations (reading/writing large files)
- Microservices & serverless apps
- Streaming applications (video/audio streaming platforms)
- Command-line tools
Example:
Companies like Flipkart use Node.js for real-time notifications, and Paytm uses it for scalable APIs.