Node.js provides several features that make it popular for backend development.
const fs = require('fs');
console.log('Start');
fs.readFile('sample.txt', 'utf8', (err, data) => {
console.log(data);
});
console.log('End');Start
End
<contents of file>The file operation executes asynchronously without blocking the application.
Streaming platforms, chat applications, and APIs use Node.js because they need to process many requests simultaneously.
Interview Tip: Non-blocking I/O and the event-driven architecture are among the most important Node.js features.
Node.js is an open-source, cross-platform JavaScript runtime environment built on Google's V8 JavaScript engine. Traditionally, JavaScript could only run inside web browsers. Node.js changed this by allowing developers to execute JavaScript on the server side.
Node.js is widely used for building REST APIs, real-time applications, microservices, streaming applications, and backend services. It follows an event-driven, non-blocking I/O architecture, which makes it highly efficient for handling multiple concurrent requests.
console.log('Hello from Node.js');node app.jsHello from Node.jsApplications like chat platforms, live notifications, online collaboration tools, and APIs often use Node.js because of its ability to handle many simultaneous connections.
Interview Tip: Node.js is a runtime environment, not a framework or programming language.
Synchronous programming executes tasks one after another. The next statement waits until the current operation completes.
Asynchronous programming allows operations to run in the background while the application continues executing other code.
const fs = require('fs');
const data = fs.readFileSync('sample.txt', 'utf8');
console.log(data);
console.log('Done');const fs = require('fs');
fs.readFile('sample.txt', 'utf8', (err, data) => {
console.log(data);
});
console.log('Done');Interview Tip: Node.js is designed around asynchronous programming because it allows handling multiple requests efficiently.
The Event Loop is the core mechanism that allows Node.js to perform asynchronous and non-blocking operations using a single JavaScript thread.
When asynchronous operations such as file reads, API calls, or database queries are initiated, Node.js delegates them to the operating system or libuv thread pool. Once completed, their callbacks are placed in a queue. The Event Loop processes these callbacks when the call stack becomes empty.
console.log('Start');
setTimeout(() => {
console.log('Timer Completed');
}, 0);
console.log('End');Start
End
Timer CompletedA web server can continue serving requests while waiting for database queries to complete.
Interview Tip: JavaScript execution is single-threaded, but Node.js uses libuv and system threads internally for asynchronous operations.
The V8 Engine is Google's high-performance JavaScript engine used in Chrome and Node.js. It converts JavaScript code directly into machine code before execution, making JavaScript applications faster.
Instead of interpreting JavaScript line by line, V8 uses Just-In-Time (JIT) compilation to improve execution speed.
function multiply(a, b) {
return a * b;
}
console.log(multiply(10, 20));200V8 compiles this JavaScript code into optimized machine code before execution.
High-performance APIs and real-time applications benefit significantly from V8's optimizations.
Interview Tip: V8 is responsible for executing JavaScript, while Node.js provides APIs for interacting with the operating system.
Strengthen your fundamentals with topic-wise MCQs designed to sharpen accuracy and speed.
npm (Node Package Manager) is the default package manager for Node.js. It provides access to a massive registry of reusable libraries and tools.
Developers use npm to install, update, remove, and manage project dependencies.
npm init
npm install express
npm uninstall express
npm updatenpm install lodashThis command downloads and installs the lodash package into the project.
Instead of writing authentication, logging, validation, and database libraries from scratch, developers can install well-tested packages using npm.
Interview Tip: npm includes both a command-line tool and an online package registry.
The package.json file is the central configuration file for a Node.js application. It stores metadata about the project, dependencies, scripts, version information, and package details.
{
'name': 'node-app',
'version': '1.0.0',
'description': 'Demo project',
'main': 'app.js',
'scripts': {
'start': 'node app.js'
},
'dependencies': {
'express': '^5.0.0'
}
}When another developer clones your project, running npm install reads package.json and installs all required dependencies.
Interview Tip: package.json is automatically generated using npm init.
Dependencies are packages required for the application to run in production. DevDependencies are packages required only during development.
npm install expressnpm install nodemon --save-dev{
'dependencies': {
'express': ^5.0.0
},
devDependencies: {
nodemon: ^3.0.0
}
}Interview Tip: Production deployments often install only dependencies, not devDependencies.
CommonJS and ES Modules are two module systems used in JavaScript and Node.js.
const math = require('./math');
module.exports = math;CommonJS is the traditional module system used by Node.js.
export function add(a, b) {
return a + b;
}
import { add } from './math.js';ES Modules are the standard JavaScript module system and are supported by modern Node.js versions.
Most new Node.js applications use ES Modules, while many older projects still rely on CommonJS.
Interview Tip: Be prepared to explain both syntaxes because many enterprise applications still use CommonJS.
A callback function is a function passed as an argument to another function and executed after a task completes. Callbacks are heavily used in Node.js because most operations such as file reading, database access, and API calls are asynchronous.
Instead of waiting for an operation to finish, Node.js registers a callback and continues executing other code. Once the operation completes, the callback function is invoked.
function greet(name, callback) {
console.log('Hello ' + name);
callback();
}
greet('John', () => {
console.log('Welcome to Node.js');
});Hello John
Welcome to Node.jsReading files, querying databases, and handling API responses often use callbacks.
Interview Tip: Understanding callbacks is important because Promises and Async/Await are built to solve callback complexity.
Paste your JD to get company insights, required skills, expected questions, and a personalized prep plan.
Callback Hell occurs when multiple asynchronous operations are nested inside one another, making the code difficult to read, maintain, and debug.
getUser(userId, function(user) {
getOrders(user.id, function(orders) {
getPayment(orders[0].id, function(payment) {
console.log(payment);
});
});
});As the application grows, nested callbacks become harder to manage.
getUser(userId)
.then(user => getOrders(user.id))
.then(orders => getPayment(orders[0].id))
.then(payment => console.log(payment));Interview Tip: Async/Await is the modern solution for avoiding Callback Hell.
Modules are reusable pieces of code that can be imported into other files. Node.js encourages modular development to improve maintainability and reusability.
Each file in Node.js is treated as a separate module.
function add(a, b) {
return a + b;
}
module.exports = add;const add = require('./math');
console.log(add(5, 3));8Interview Tip: Node.js traditionally uses the CommonJS module system with require() and module.exports.
A Promise is an object that represents the eventual success or failure of an asynchronous operation.
A Promise can be in one of three states:
const promise = new Promise((resolve, reject) => {
const success = true;
if(success) {
resolve('Operation Successful');
} else {
reject('Operation Failed');
}
});
promise
.then(result => console.log(result))
.catch(error => console.log(error));Operation SuccessfulInterview Tip: Promises are the foundation of Async/Await.
Async/Await is a modern syntax introduced to simplify working with Promises. It makes asynchronous code look and behave like synchronous code.
fetchData()
.then(data => console.log(data));async function getData() {
const data = await fetchData();
console.log(data);
}
getData();async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch(error) {
console.log(error.message);
}
}Interview Tip: Await can only be used inside async functions.
A Buffer is a temporary memory area used to store binary data directly in memory. JavaScript traditionally works with strings and objects, but Buffers allow Node.js to work efficiently with files, images, videos, and network data.
const buffer = Buffer.from('Hello');
console.log(buffer);
console.log(buffer.toString());<Buffer 48 65 6c 6c 6f>
HelloInterview Tip: Buffers are commonly used behind the scenes when working with streams.
Practice with expert evaluators and receive detailed feedback to improve instantly.
Streams allow data to be processed piece by piece instead of loading an entire file into memory. This improves performance and reduces memory consumption.
const fs = require('fs');
const readStream = fs.createReadStream('large-file.txt');
readStream.on('data', chunk => {
console.log(chunk.toString());
});Video streaming platforms use streams to deliver content progressively instead of loading entire files into memory.
Interview Tip: Streams are one of Node.js's strongest features for handling large datasets.
The fs module allows Node.js applications to interact with the file system. It provides methods for reading, writing, updating, deleting, and managing files and directories.
const fs = require('fs');
fs.readFile('sample.txt', 'utf8', (err, data) => {
if(err) {
console.log(err);
return;
}
console.log(data);
});fs.writeFile('sample.txt', 'Hello Node.js', err => {
if(err) throw err;
console.log('File saved');
});Log files, report generation, configuration management, and file uploads.
Interview Tip: Always prefer asynchronous fs methods in production applications.
The path module provides utilities for working with file and directory paths in a platform-independent way.
const path = require('path');
const filePath = path.join('users', 'documents', 'file.txt');
console.log(filePath);users/documents/file.txtUsed when managing uploads, generating file paths, and reading configuration files.
Interview Tip: path.join() is preferred over manual string concatenation because it works across operating systems.
Error handling is essential for building reliable applications. Node.js supports error handling through callbacks, Promises, Async/Await, and try-catch blocks.
try {
throw new Error('Something went wrong');
} catch(error) {
console.log(error.message);
}Something went wrongasync function getData() {
try {
const result = await fetchData();
console.log(result);
} catch(error) {
console.log(error.message);
}
}Interview Tip: Unhandled Promise rejections can crash applications in modern Node.js versions.
The EventEmitter class is part of the events module and is used to create, emit, and listen to custom events.
Many built-in Node.js modules such as streams and HTTP servers are based on EventEmitter.
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('userCreated', user => {
console.log('User Created:', user);
});
emitter.emit('userCreated', 'John');User Created: JohnInterview Tip: EventEmitter follows the publish-subscribe pattern.
Strengthen your fundamentals with topic-wise MCQs designed to sharpen accuracy and speed.
Routing determines how an application responds to a client request for a particular endpoint and HTTP method.
Each route consists of a URL path and an associated callback function that executes when the route is matched.
const express = require('express');
const app = express();
app.get('/users', (req, res) => {
res.send('Get All Users');
});
app.post('/users', (req, res) => {
res.send('Create User');
});Interview Tip: Routing is one of the core concepts in REST API development.
Middleware functions are functions that execute during the request-response cycle. They have access to the request object, response object, and the next middleware function.
Middleware can perform logging, authentication, validation, request transformation, and error handling.
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Request Received');
next();
});
app.get('/', (req, res) => {
res.send('Home Page');
});Interview Tip: Forgetting to call next() can cause requests to hang indefinitely.
Express.js is a lightweight and flexible web application framework built on top of Node.js. While Node.js provides low-level APIs for handling HTTP requests and responses, Express simplifies web development by providing routing, middleware support, request processing, and many utility features.
Without Express, developers would need to write a significant amount of boilerplate code to build APIs and web applications.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Express');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});Most Node.js backend applications and REST APIs are built using Express because it significantly reduces development effort.
Interview Tip: Express is a framework built on Node.js, not a replacement for Node.js.
req.query is used to access query string parameters from the URL.
Query parameters are commonly used for filtering, searching, sorting, and pagination.
app.get('/users', (req, res) => {
console.log(req.query);
res.send(req.query);
});GET /users?page=1&limit=10{
'page': '1',
'limit': '10'
}Interview Tip: Query parameters are optional and appear after the ? symbol in a URL.
req.params is used to access route parameters from the URL.
Route parameters are part of the URL path and are commonly used to identify resources.
app.get('/users/:id', (req, res) => {
res.send(req.params.id);
});GET /users/101101Interview Tip: req.params retrieves values from the URL path, not from query strings.
Paste your JD to get company insights, required skills, expected questions, and a personalized prep plan.
req.body contains data sent by the client in the request body. It is commonly used in POST, PUT, and PATCH requests.
To access req.body, Express must be configured with body parsing middleware.
const express = require('express');
const app = express();
app.use(express.json());
app.post('/users', (req, res) => {
console.log(req.body);
res.send(req.body);
});{
'name': 'John',
'email': '[email protected]'
}Interview Tip: express.json() is required to parse JSON request bodies.
GET and POST are HTTP methods used for different purposes.
app.get('/users', (req, res) => {
res.send('Get Users');
});
app.post('/users', (req, res) => {
res.send('Create User');
});Interview Tip: Sensitive information should not be sent using GET query parameters.
REST (Representational State Transfer) is an architectural style used for designing web services. REST APIs use HTTP methods to perform operations on resources.
GET /users
POST /users
PUT /users/1
DELETE /users/1Interview Tip: Most Node.js backend applications expose functionality through REST APIs.
process.nextTick() schedules a callback to execute immediately after the current operation completes and before the event loop continues.
It has higher priority than timers such as setTimeout().
console.log('Start');
process.nextTick(() => {
console.log('Next Tick');
});
setTimeout(() => {
console.log('Timeout');
}, 0);
console.log('End');Start
End
Next Tick
TimeoutInterview Tip: process.nextTick() callbacks execute before timer callbacks.
Node.js executes JavaScript on a single thread. The Cluster module allows applications to utilize multiple CPU cores by creating worker processes.
Each worker can handle incoming requests independently, improving scalability and performance.
const cluster = require('cluster');
const os = require('os');
if (cluster.isPrimary) {
const cpuCount = os.cpus().length;
for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}
} else {
console.log(`Worker ${process.pid} started`);
}High-traffic APIs and web servers often use clustering to maximize server resources.
Interview Tip: Cluster creates multiple processes, not multiple threads.
Practice with expert evaluators and receive detailed feedback to improve instantly.