Top Node JS Interview Questions

nodejsfeatures

Node.js provides several features that make it popular for backend development.

Key Features

  • Asynchronous and Event-Driven: Supports non-blocking operations.
  • Single-Threaded Event Loop: Efficiently handles multiple requests.
  • High Performance: Uses Google's V8 engine.
  • Scalable: Suitable for microservices and distributed systems.
  • Cross Platform: Runs on Windows, Linux, and macOS.
  • Large Ecosystem: Access to millions of npm packages.

Example

const fs = require('fs');

console.log('Start');

fs.readFile('sample.txt', 'utf8', (err, data) => {
  console.log(data);
});

console.log('End');

Output

Start
End
<contents of file>

The file operation executes asynchronously without blocking the application.

Real-World Use Case

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.

nodejsjavascriptruntime

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.

Why Use Node.js?

  • Write frontend and backend code in JavaScript.
  • Fast execution using the V8 engine.
  • Handles thousands of concurrent requests efficiently.
  • Large ecosystem through npm.
  • Ideal for real-time applications such as chat systems.

Example

console.log('Hello from Node.js');

Run

node app.js

Output

Hello from Node.js

Real-World Use Case

Applications 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.

nodejssynchronousasynchronous

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.

Synchronous Example

const fs = require('fs');

const data = fs.readFileSync('sample.txt', 'utf8');
console.log(data);
console.log('Done');

Asynchronous Example

const fs = require('fs');

fs.readFile('sample.txt', 'utf8', (err, data) => {
  console.log(data);
});

console.log('Done');

Benefits of Asynchronous Programming

  • Better performance.
  • Improved scalability.
  • Non-blocking execution.

Interview Tip: Node.js is designed around asynchronous programming because it allows handling multiple requests efficiently.

nodejsevent-loopasync

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.

Execution Flow

  1. Execute synchronous code.
  2. Register asynchronous operations.
  3. Move completed callbacks to callback queue.
  4. Event Loop checks the call stack.
  5. Execute queued callbacks.

Example

console.log('Start');

setTimeout(() => {
  console.log('Timer Completed');
}, 0);

console.log('End');

Output

Start
End
Timer Completed

Real-World Use Case

A 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.

nodejsv8javascript

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.

Benefits of V8

  • Fast execution.
  • Efficient memory management.
  • Optimized garbage collection.
  • Improved application performance.

Example

function multiply(a, b) {
  return a * b;
}

console.log(multiply(10, 20));

Output

200

V8 compiles this JavaScript code into optimized machine code before execution.

Real-World Use Case

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.

Master Concepts with Targeted MCQs

Strengthen your fundamentals with topic-wise MCQs designed to sharpen accuracy and speed.

nodejsnpmpackage-manager

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.

Common Commands

npm init
npm install express
npm uninstall express
npm update

Example

npm install lodash

This command downloads and installs the lodash package into the project.

Real-World Use Case

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.

nodejspackage-jsonnpm

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.

Example

{
  'name': 'node-app',
  'version': '1.0.0',
  'description': 'Demo project',
  'main': 'app.js',
  'scripts': {
    'start': 'node app.js'
  },
  'dependencies': {
    'express': '^5.0.0'
  }
}

Important Properties

  • name
  • version
  • scripts
  • dependencies
  • devDependencies

Real-World Use Case

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.

nodejsnpmdependencies

Dependencies are packages required for the application to run in production. DevDependencies are packages required only during development.

Installing Dependencies

npm install express

Installing Dev Dependencies

npm install nodemon --save-dev

Example package.json

{
  'dependencies': {
    'express': ^5.0.0
  },
  devDependencies: {
    nodemon: ^3.0.0
  }
}

Use Cases

  • Express: Production dependency.
  • Nodemon: Development dependency.
  • ESLint: Development dependency.

Interview Tip: Production deployments often install only dependencies, not devDependencies.

nodejscommonjsesmodules

CommonJS and ES Modules are two module systems used in JavaScript and Node.js.

CommonJS

const math = require('./math');
module.exports = math;

CommonJS is the traditional module system used by Node.js.

ES Modules

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.

Key Differences

  • CommonJS uses require and module.exports.
  • ES Modules use import and export.
  • ES Modules support static analysis and tree shaking.
  • ES Modules are the future standard.

Real-World Use Case

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.

nodejscallbackasync

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.

Example

function greet(name, callback) {
  console.log('Hello ' + name);
  callback();
}

greet('John', () => {
  console.log('Welcome to Node.js');
});

Output

Hello John
Welcome to Node.js

Real-World Use Case

Reading 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.

Turn Any Job Description Into an Interview Strategy

Paste your JD to get company insights, required skills, expected questions, and a personalized prep plan.

nodejscallbackasyncpromise

Callback Hell occurs when multiple asynchronous operations are nested inside one another, making the code difficult to read, maintain, and debug.

Example of Callback Hell

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.

Solution Using Promises

getUser(userId)
  .then(user => getOrders(user.id))
  .then(orders => getPayment(orders[0].id))
  .then(payment => console.log(payment));

Benefits

  • Improved readability.
  • Easier debugging.
  • Better error handling.

Interview Tip: Async/Await is the modern solution for avoiding Callback Hell.

nodejsmodulescommonjs

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.

Create Module

function add(a, b) {
  return a + b;
}

module.exports = add;

Import Module

const add = require('./math');

console.log(add(5, 3));

Output

8

Benefits

  • Code reusability.
  • Better organization.
  • Easier maintenance.

Interview Tip: Node.js traditionally uses the CommonJS module system with require() and module.exports.

nodejspromiseasync

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:

  • Pending
  • Fulfilled
  • Rejected

Example

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));

Output

Operation Successful

Benefits

  • Cleaner asynchronous code.
  • Better error handling.
  • Avoids Callback Hell.

Interview Tip: Promises are the foundation of Async/Await.

nodejsasync-awaitpromise

Async/Await is a modern syntax introduced to simplify working with Promises. It makes asynchronous code look and behave like synchronous code.

Example Using Promise

fetchData()
  .then(data => console.log(data));

Example Using Async/Await

async function getData() {
  const data = await fetchData();
  console.log(data);
}

getData();

Error Handling

async function getData() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch(error) {
    console.log(error.message);
  }
}

Benefits

  • Readable code.
  • Easy debugging.
  • Cleaner error handling.

Interview Tip: Await can only be used inside async functions.

nodejsbufferbinary-data

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.

Example

const buffer = Buffer.from('Hello');

console.log(buffer);
console.log(buffer.toString());

Output

<Buffer 48 65 6c 6c 6f>
Hello

Use Cases

  • File processing.
  • Image uploads.
  • Network communication.
  • Streaming data.

Interview Tip: Buffers are commonly used behind the scenes when working with streams.

Experience a Real Interview

Practice with expert evaluators and receive detailed feedback to improve instantly.

nodejsstreamsperformance

Streams allow data to be processed piece by piece instead of loading an entire file into memory. This improves performance and reduces memory consumption.

Types of Streams

  • Readable
  • Writable
  • Duplex
  • Transform

Example

const fs = require('fs');

const readStream = fs.createReadStream('large-file.txt');

readStream.on('data', chunk => {
  console.log(chunk.toString());
});

Benefits

  • Memory efficient.
  • Faster processing.
  • Suitable for large files.

Real-World Use Case

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.

nodejsfsfile-system

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.

Reading a File

const fs = require('fs');

fs.readFile('sample.txt', 'utf8', (err, data) => {
  if(err) {
    console.log(err);
    return;
  }

  console.log(data);
});

Writing a File

fs.writeFile('sample.txt', 'Hello Node.js', err => {
  if(err) throw err;
  console.log('File saved');
});

Real-World Use Case

Log files, report generation, configuration management, and file uploads.

Interview Tip: Always prefer asynchronous fs methods in production applications.

nodejspathmodule

The path module provides utilities for working with file and directory paths in a platform-independent way.

Example

const path = require('path');

const filePath = path.join('users', 'documents', 'file.txt');

console.log(filePath);

Output

users/documents/file.txt

Common Methods

  • path.join()
  • path.resolve()
  • path.basename()
  • path.dirname()
  • path.extname()

Real-World Use Case

Used 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.

nodejserror-handlingexceptions

Error handling is essential for building reliable applications. Node.js supports error handling through callbacks, Promises, Async/Await, and try-catch blocks.

Using Try-Catch

try {
  throw new Error('Something went wrong');
} catch(error) {
  console.log(error.message);
}

Output

Something went wrong

Using Async/Await

async function getData() {
  try {
    const result = await fetchData();
    console.log(result);
  } catch(error) {
    console.log(error.message);
  }
}

Best Practices

  • Always handle Promise rejections.
  • Use centralized error handling.
  • Log errors for troubleshooting.
  • Do not expose sensitive information to users.

Interview Tip: Unhandled Promise rejections can crash applications in modern Node.js versions.

nodejseventemitterevents

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.

Example

const EventEmitter = require('events');

const emitter = new EventEmitter();

emitter.on('userCreated', user => {
  console.log('User Created:', user);
});

emitter.emit('userCreated', 'John');

Output

User Created: John

Use Cases

  • Notifications.
  • Logging.
  • Application events.
  • Workflow processing.

Interview Tip: EventEmitter follows the publish-subscribe pattern.

Master Concepts with Targeted MCQs

Strengthen your fundamentals with topic-wise MCQs designed to sharpen accuracy and speed.

nodejsexpressrouting

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.

Example

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');
});

Common HTTP Methods

  • GET - Retrieve data.
  • POST - Create data.
  • PUT - Update data.
  • DELETE - Remove data.

Interview Tip: Routing is one of the core concepts in REST API development.

nodejsexpressmiddleware

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.

Example

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');
});

Types of Middleware

  • Application Middleware
  • Router Middleware
  • Error Middleware
  • Third-party Middleware

Interview Tip: Forgetting to call next() can cause requests to hang indefinitely.

nodejsexpressweb-framework

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.

Benefits of Express.js

  • Simplified routing.
  • Middleware support.
  • REST API development.
  • Template engine integration.
  • Easy request and response handling.

Example

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');
});

Real-World Use Case

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.

nodejsexpressreq-query

req.query is used to access query string parameters from the URL.

Query parameters are commonly used for filtering, searching, sorting, and pagination.

Example

app.get('/users', (req, res) => {
  console.log(req.query);
  res.send(req.query);
});

Request

GET /users?page=1&limit=10

Output

{
  'page': '1',
  'limit': '10'
}

Interview Tip: Query parameters are optional and appear after the ? symbol in a URL.

nodejsexpressreq-params

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.

Example

app.get('/users/:id', (req, res) => {
  res.send(req.params.id);
});

Request

GET /users/101

Output

101

Interview Tip: req.params retrieves values from the URL path, not from query strings.

Turn Any Job Description Into an Interview Strategy

Paste your JD to get company insights, required skills, expected questions, and a personalized prep plan.

nodejsexpressreq-body

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.

Example

const express = require('express');
const app = express();

app.use(express.json());

app.post('/users', (req, res) => {
  console.log(req.body);
  res.send(req.body);
});

Request Body

{
  'name': 'John',
  'email': '[email protected]'
}

Interview Tip: express.json() is required to parse JSON request bodies.

nodejshttpgetpost

GET and POST are HTTP methods used for different purposes.

GET

  • Used to retrieve data.
  • Data is sent in the URL.
  • Can be cached.

POST

  • Used to create resources.
  • Data is sent in the request body.
  • Generally not cached.

Example

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.

nodejsrestapi

REST (Representational State Transfer) is an architectural style used for designing web services. REST APIs use HTTP methods to perform operations on resources.

HTTP Methods

  • GET - Read data.
  • POST - Create data.
  • PUT - Update data.
  • DELETE - Delete data.

Example

GET /users
POST /users
PUT /users/1
DELETE /users/1

Benefits

  • Simple and scalable.
  • Platform independent.
  • Widely adopted.

Interview Tip: Most Node.js backend applications expose functionality through REST APIs.

nodejsevent-loopnexttick

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().

Example

console.log('Start');

process.nextTick(() => {
  console.log('Next Tick');
});

setTimeout(() => {
  console.log('Timeout');
}, 0);

console.log('End');

Output

Start
End
Next Tick
Timeout

Interview Tip: process.nextTick() callbacks execute before timer callbacks.

nodejsclusterperformance

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.

Example

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`);
}

Benefits

  • Uses all CPU cores.
  • Improves throughput.
  • Provides better fault tolerance.

Real-World Use Case

High-traffic APIs and web servers often use clustering to maximize server resources.

Interview Tip: Cluster creates multiple processes, not multiple threads.

Experience a Real Interview

Practice with expert evaluators and receive detailed feedback to improve instantly.

💬