1. What is Node.js?

Node.js is a runtime environment that allows JavaScript to run outside the browser, mainly for backend development.

It is built on the V8 Engine, which compiles JavaScript into machine code.

In simple terms:
Node.js lets you use JavaScript to build servers, APIs, and backend systems.

Example:

const http = require('http');

http.createServer((req, res) => {
res.end("Hello World");
}).listen(3000);

2. Why should we use Node.js?

Node.js is used because it is fast, scalable, and efficient for modern applications.

Key reasons:

  • Uses V8 engine → fast execution
  • Non-blocking I/O → handles many users efficiently
  • Single language (JavaScript) for frontend and backend
  • Large ecosystem (npm)
  • Good for real-time applications

Best use cases:

  • REST APIs
  • Chat applications
  • Streaming services
  • Microservices

3. How does Node.js work internally?

Node.js works on an event-driven, non-blocking architecture.

Internal flow:

  1. Request comes to server
  2. Event loop receives the request
  3. If task is simple → executed immediately
  4. If task involves I/O → sent to background (thread pool via libuv)
  5. When task finishes → callback added to queue
  6. Event loop executes callback

Key components:

  • Event Loop
  • Callback Queue
  • Thread Pool (libuv)

Example:

console.log("Start");

setTimeout(() => {
console.log("Async task done");
}, 1000);

console.log("End");

Output:

Start
End
Async task done

4. How is Node.js different from a browser runtime?

FeatureNode.jsBrowser
PurposeBackendFrontend
APIsFile system, OS, networkDOM, UI
Global objectglobalwindow
AccessFull system accessRestricted
ModulesCommonJS/ESMESM

Example:

  • Node.js → fs.readFile()
  • Browser → document.getElementById()

5. Why is Node.js single-threaded?

Node.js uses a single thread to run the event loop.

Reason:

  • Avoids overhead of multiple threads
  • Efficient for I/O-heavy tasks
  • Easier to manage concurrency

Important point:
Single-threaded does not mean it can handle only one request. It can handle many requests using asynchronous processing.


6. If Node.js is single-threaded, how does it handle concurrency?

Node.js handles concurrency using:

  • Event Loop
  • Asynchronous callbacks / promises
  • Background thread pool (libuv)

Flow:

  • Main thread receives all requests
  • I/O tasks are sent to thread pool
  • Main thread continues processing other requests
  • When task finishes → result returned via callback

Example:

const fs = require('fs');

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

console.log("Reading...");

Output:

Reading...
(file content later)

7. What is the V8 engine?

V8 Engine is a JavaScript engine developed by Google.

Function:

  • Converts JavaScript into machine code
  • Uses Just-In-Time (JIT) compilation
  • Improves performance

8. Why does Node.js use the V8 engine?

Node.js uses V8 because:

  • High performance
  • Fast execution (JIT compilation)
  • Efficient memory management
  • Already tested in browsers like Chrome

9. What is I/O in Node.js?

I/O means Input and Output operations.

These are operations where data moves between the program and external sources.

Examples:

  • File reading/writing
  • Database queries
  • API calls
  • Network requests

Example:

const fs = require('fs');

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

10. What is non-blocking I/O?

Non-blocking I/O means Node.js does not wait for a task to complete before moving to the next task.

Instead:

  • It registers a callback
  • Continues execution
  • Executes callback when task is finished

Blocking example:

const data = fs.readFileSync('file.txt');
console.log(data);
console.log("Done");

Here execution stops until file is read.

Non-blocking example:

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

console.log("Done");

Output:

Done
(file data later)

11. Difference between blocking and non-blocking code

Blocking code:
Execution stops until the current operation completes.

Non-blocking code:
Execution continues without waiting; the result is handled later using callbacks, promises, or async/await.

Key difference:

BlockingNon-blocking
Waits for task completionDoes not wait
Slower for I/O tasksEfficient for multiple requests
Sequential executionConcurrent execution

Example:

// Blocking
const fs = require('fs');
const data = fs.readFileSync('file.txt');
console.log(data);
console.log("Done");
// Non-blocking
fs.readFile('file.txt', (err, data) => {
console.log(data);
});
console.log("Done");

12. Difference between synchronous and asynchronous execution

Synchronous execution:
Tasks execute one after another in sequence. Each step waits for the previous one.

Asynchronous execution:
Tasks can start and continue independently; results are handled later.

Key difference:

SynchronousAsynchronous
SequentialNon-sequential
BlockingNon-blocking
Simple flowRequires callbacks/promises

Example:

// Synchronous
console.log("A");
console.log("B");
console.log("C");
// Asynchronous
console.log("A");

setTimeout(() => {
console.log("B");
}, 0);

console.log("C");

Output:

A
C
B

13. What is event-driven programming?

Event-driven programming is a paradigm where the flow of execution is controlled by events such as user actions, API responses, or timers.

Node.js heavily uses this model.

How it works:

  • An event occurs
  • A listener detects it
  • A callback function is executed

Example:

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('greet', () => {
console.log("Hello user");
});

emitter.emit('greet');

14. What is control flow in Node.js?

Control flow refers to the order in which code is executed, especially when handling asynchronous operations.

In Node.js, managing control flow is important because multiple operations can run in parallel.

Common control flow patterns:

  • Callbacks
  • Promises
  • Async/await

Example:

fs.readFile('file.txt', (err, data) => {
if (err) throw err;

processData(data);
});

15. What is a control flow function?

A control flow function helps manage the execution order of multiple asynchronous tasks.

It ensures tasks run:

  • In sequence
  • In parallel
  • With proper error handling

Example (manual sequencing):

function step1(cb) {
console.log("Step 1");
cb();
}

function step2(cb) {
console.log("Step 2");
cb();
}

step1(() => {
step2(() => {
console.log("Done");
});
});

In real projects, libraries or promises are used to simplify this.


16. What are callbacks?

A callback is a function passed as an argument to another function and executed later.

It is widely used in asynchronous programming.

Example:

function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}

fetchData((data) => {
console.log(data);
});

17. What is an error-first callback?

In Node.js, callbacks follow a standard pattern:

callback(error, result)
  • First parameter → error
  • Second parameter → result

Why:

It provides a consistent way to handle errors.

Example:

const fs = require('fs');

fs.readFile('file.txt', (err, data) => {
if (err) {
console.error("Error:", err);
return;
}
console.log(data);
});

18. What is callback hell?

Callback hell occurs when multiple nested callbacks make code hard to read and maintain.

Problem:

  • Deep nesting
  • Difficult debugging
  • Poor readability

Example:

step1(() => {
step2(() => {
step3(() => {
step4(() => {
console.log("Done");
});
});
});
});

Solution:

  • Promises
  • Async/await

19. What are first-class functions?

In JavaScript, functions are treated as first-class citizens.

This means:

  • Functions can be assigned to variables
  • Passed as arguments
  • Returned from other functions

Example:

function greet() {
return "Hello";
}

function execute(fn) {
console.log(fn());
}

execute(greet);

20. What is closure?

A closure is a function that remembers variables from its outer scope even after the outer function has finished execution.

Key idea:

Inner function retains access to outer variables.

Example:

function outer() {
let count = 0;

return function inner() {
count++;
console.log(count);
};
}

const counter = outer();

counter(); // 1
counter(); // 2

Explanation:

  • inner function keeps access to count
  • Even after outer execution is complete
  • This is called closure

Use cases:

  • Data privacy
  • Function factories
  • Maintaining state

21. What is lexical scope?

Lexical scope means that the accessibility of variables is determined by where they are declared in the code (at write time), not where they are called.

Inner functions can access variables from their outer scope.

Example:

function outer() {
let name = "Node";

function inner() {
console.log(name);
}

inner();
}

outer();

Explanation:

  • inner is defined inside outer
  • It can access name because of lexical scope

22. What is hoisting?

Hoisting is JavaScript's behavior of moving declarations to the top of their scope before execution.

Important points:

  • var is hoisted and initialized with undefined
  • let and const are hoisted but not initialized (Temporal Dead Zone)

Example:

console.log(x); // undefined
var x = 10;

Internally behaves like:

var x;
console.log(x);
x = 10;

Example with let:

console.log(a); // ReferenceError
let a = 5;

23. Difference between var, let, and const

Featurevarletconst
ScopeFunctionBlockBlock
Re-declareYesNoNo
Re-assignYesYesNo
HoistingYes (undefined)Yes (TDZ)Yes (TDZ)

Example:

var x = 1;
var x = 2; // allowed

let y = 1;
// let y = 2; // error

const z = 1;
// z = 2; // error

24. Difference between == and ===

== (loose equality):

  • Compares values after type conversion

=== (strict equality):

  • Compares value and type, no conversion

Example:

console.log(5 == "5");  // true
console.log(5 === "5"); // false

Best practice: Always use === to avoid unexpected behavior.


25. What is the global object in Node.js?

The global object in Node.js is global.

It provides globally available variables and functions.

Examples:

  • setTimeout()
  • setInterval()
  • __dirname
  • __filename

Example:

console.log(global);

Important difference:

  • In browser → window
  • In Node.js → global

26. What is the Event Loop?

The Event Loop is the core mechanism in Node.js that continuously checks and executes tasks from the queue.

It enables Node.js to handle asynchronous operations using a single thread.

Working:

  1. Executes synchronous code
  2. Checks callback queue
  3. Executes pending callbacks

Example:

console.log("Start");

setTimeout(() => {
console.log("Callback");
}, 0);

console.log("End");

Output:

Start
End
Callback

27. What is the role of the event queue?

The event queue (callback queue) stores callbacks of completed asynchronous operations.

Flow:

  • Async task completes
  • Callback added to queue
  • Event loop picks and executes it

Example concept:

  • setTimeout, fs.readFile, API calls → push callbacks to queue

28. How does Node.js handle multiple requests concurrently?

Node.js handles concurrency using:

  • Event Loop
  • Non-blocking I/O
  • Background thread pool (libuv)

Flow:

  1. Multiple requests arrive
  2. Event loop assigns tasks
  3. I/O tasks go to thread pool
  4. Main thread continues processing
  5. Completed tasks return via callbacks

Key idea:
Node.js does not create a new thread per request; it uses async processing.


29. What are Promises?

A Promise is an object that represents the future result of an asynchronous operation.

States:

  • Pending
  • Fulfilled
  • Rejected

Example:

const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Success");
}, 1000);
});

promise.then(result => {
console.log(result);
});

30. What problem do Promises solve?

Promises solve problems of callback-based asynchronous code, mainly:

Problems:

  • Callback hell (deep nesting)
  • Poor readability
  • Difficult error handling

Solution:

  • Chainable .then()
  • Centralized error handling with .catch()
  • Cleaner flow

Callback hell example:

step1(() => {
step2(() => {
step3(() => {
console.log("Done");
});
});
});

Promise solution:

step1()
.then(step2)
.then(step3)
.then(() => console.log("Done"))
.catch(err => console.error(err));

31. What is promise chaining?

Promise chaining means executing multiple asynchronous operations in sequence, where each step depends on the previous one.

It is done using .then().

Why it is used:

  • Avoid nested callbacks
  • Maintain readable flow
  • Handle sequential async tasks

Example:

function step1() {
return Promise.resolve("Step 1 done");
}

function step2(data) {
return Promise.resolve(data + " → Step 2 done");
}

function step3(data) {
return Promise.resolve(data + " → Step 3 done");
}

step1()
.then(step2)
.then(step3)
.then(result => console.log(result))
.catch(err => console.error(err));

Key idea:
Each .then() returns a new promise, enabling chaining.


32. What is async/await?

async/await is a modern way to handle asynchronous operations in JavaScript.

  • async makes a function return a Promise
  • await pauses execution until the Promise resolves

Example:

function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve("Data received"), 1000);
});
}

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

getData();

33. How does async/await improve readability?

async/await makes asynchronous code look like synchronous code.

Problems with Promises:

  • Multiple .then() calls
  • Harder to read and debug

With async/await:

  • Linear, top-to-bottom flow
  • Easier error handling using try...catch

Example comparison:

Using Promises:

getUser()
.then(user => getOrders(user))
.then(orders => getPayment(orders))
.then(payment => console.log(payment))
.catch(err => console.error(err));

Using async/await:

async function process() {
try {
const user = await getUser();
const orders = await getOrders(user);
const payment = await getPayment(orders);
console.log(payment);
} catch (err) {
console.error(err);
}
}

34. What are modules in Node.js?

Modules are reusable pieces of code that are organized into separate files.

They help in:

  • Code reusability
  • Better structure
  • Maintainability

Node.js treats each file as a module.


35. What is CommonJS?

CommonJS is the default module system used in Node.js.

It uses:

  • require() to import
  • module.exports to export

Example:

math.js

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

module.exports = add;

app.js

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

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

36. What are ES Modules?

ES Modules (ESM) are the modern JavaScript module system.

They use:

  • import and export

Example:

math.js

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

app.js

import { add } from './math.js';

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

37. What is require()?

require() is a function used in CommonJS to import modules.

Features:

  • Loads module synchronously
  • Caches modules after first load

Example:

const fs = require('fs');

38. How do you import a module in Node.js?

There are two ways:

Using CommonJS:

const module = require('./file');

Using ES Modules:

import module from './file.js';

39. Difference between exports and module.exports

Both are used to export data from a module, but they behave differently.

Key difference:

exportsmodule.exports
Shortcut referenceActual object exported
Cannot replace objectCan replace entire object
Limited usePreferred

Example:

// exports
exports.a = 10;
exports.b = 20;
// module.exports
module.exports = {
a: 10,
b: 20
};

Important:

exports = { a: 10 }; // This will NOT work

40. What is NPM?

npm (Node Package Manager) is the default package manager for Node.js.

It is used for:

  • Installing libraries
  • Managing dependencies
  • Running scripts

Key features:

  • Largest package ecosystem
  • Version management
  • CLI tool

Example:

Install a package:

npm install express

Use it:

const express = require('express');

41. What are the main functions of NPM?

npm is the default package manager for Node.js.

Main functions:

  1. Dependency management
    Install and manage third-party libraries.
  2. Version control
    Handle different versions using semantic versioning.
  3. Script execution
    Run predefined scripts (build, start, test).
  4. Package publishing
    Publish your own packages to the npm registry.
  5. Project configuration
    Manage metadata via package.json.

42. What is package.json?

package.json is the main configuration file of a Node.js project.

It contains:

  • Project name and version
  • Dependencies and devDependencies
  • Scripts
  • Metadata

Example:

{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "^4.18.0"
}
}

Purpose:

  • Defines project structure
  • Tracks dependencies
  • Enables reproducibility

43. What is node_modules?

node_modules is the directory where all installed packages are stored.

Key points:

  • Created automatically after npm install
  • Contains all dependencies and their sub-dependencies
  • Can be very large
  • Usually ignored in version control (.gitignore)

44. Difference between local and global package installation

FeatureLocal InstallationGlobal Installation
ScopeProject-specificSystem-wide
Locationnode_modulesGlobal directory
UsageUsed in project codeUsed as CLI tools
Commandnpm install packagenpm install -g package

Example:

  • Local → express
  • Global → nodemon, npm, typescript

45. How do you install, update, and remove dependencies?

Install:

npm install package-name

Install specific version:

npm install package-name@1.2.0

Update:

npm update package-name

Remove:

npm uninstall package-name

46. Difference between npm and yarn

npm vs Yarn

FeaturenpmYarn
SpeedModerateFaster (parallel installs)
Lock filepackage-lock.jsonyarn.lock
InstallationSequential (older versions)Parallel
Offline supportLimitedBetter
StabilityImproved in newer versionsStable

Summary:
Both are package managers. Yarn focuses on speed and consistency, while npm is the default and widely used.


47. What is the fs module?

fs (File System) module is a built-in Node.js module used to interact with the file system.

Operations:

  • Read files
  • Write files
  • Delete files
  • Manage directories

Example:

const fs = require('fs');

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

48. Difference between synchronous and asynchronous fs methods

SynchronousAsynchronous
BlockingNon-blocking
Waits for completionExecutes in background
Slower for large tasksEfficient
Uses Sync methodsUses callbacks/promises

Example:

Synchronous:

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

Asynchronous:

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

console.log("Done");

49. What is a Buffer?

A Buffer is a temporary memory area used to store raw binary data.

In Node.js, buffers are used when dealing with:

  • Files
  • Streams
  • Network data

JavaScript normally handles strings, but buffers allow handling of binary data directly.

Example:

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

console.log(buffer);

50. When is Buffer used?

Buffers are used when working with low-level data handling.

Common use cases:

  1. File operations
    Reading/writing binary files (images, videos)
  2. Network communication
    Handling data packets
  3. Streams
    Processing data chunk by chunk
  4. Encoding/decoding
    Converting between formats (UTF-8, base64)

Example:

const buf = Buffer.from("Hello");
console.log(buf.toString()); // Hello

51. What are streams?

Streams are objects in Node.js used to process data piece by piece (in chunks) instead of loading the entire data into memory at once.

Why streams are important:

  • Efficient for large data (files, videos)
  • Memory optimization
  • Faster processing

Example idea:
Instead of reading a 1GB file at once, streams read it in small chunks.


52. Types of streams in Node.js

There are four main types of streams:

  1. Readable → read data
  2. Writable → write data
  3. Duplex → read and write
  4. Transform → modify data while reading/writing

Example:

const fs = require('fs');

const readStream = fs.createReadStream('file.txt');
const writeStream = fs.createWriteStream('copy.txt');

readStream.pipe(writeStream);

53. Difference between readFile() and createReadStream()

readFile()createReadStream()
Reads entire file at onceReads file in chunks
High memory usageLow memory usage
Blocking (large files)Efficient for large files
Simple to useMore control

Example:

// readFile
fs.readFile('file.txt', (err, data) => {
console.log(data);
});
// createReadStream
const stream = fs.createReadStream('file.txt');
stream.on('data', chunk => {
console.log(chunk);
});

54. What is piping in Node.js?

Piping is a mechanism to connect streams together, where output of one stream becomes input of another.

Advantage:

  • Efficient data transfer
  • Less manual handling

Example:

const fs = require('fs');

fs.createReadStream('input.txt')
.pipe(fs.createWriteStream('output.txt'));

55. What is backpressure in streams?

Backpressure occurs when a readable stream produces data faster than a writable stream can consume it.

Problem:

  • Memory overflow
  • Performance issues

Solution:

  • Node.js automatically manages backpressure using internal buffering and flow control
  • Streams pause and resume based on speed

56. How do you create a simple HTTP server in Node.js?

Node.js provides a built-in http module to create servers.

Example:

const http = require('http');

const server = http.createServer((req, res) => {
res.write("Hello World");
res.end();
});

server.listen(3000, () => {
console.log("Server running on port 3000");
});

57. What are the different types of HTTP requests?

Common HTTP methods:

  • GET → retrieve data
  • POST → send data
  • PUT → update data
  • PATCH → partial update
  • DELETE → remove data

Example:

if (req.method === "GET") {
res.end("GET request");
}

58. What are Node.js API functions?

Node.js API functions are built-in functions provided by Node.js modules to perform various operations.

Examples:

  • fs.readFile() → file handling
  • http.createServer() → server creation
  • setTimeout() → timers

59. How many types of API functions exist in Node.js?

There are mainly two types:

  1. Synchronous APIs
    • Blocking
    • Execute one task at a time
  2. Asynchronous APIs
    • Non-blocking
    • Use callbacks, promises, async/await

Example:

// Synchronous
fs.readFileSync('file.txt');

// Asynchronous
fs.readFile('file.txt', () => {});

60. What is middleware?

Middleware is a function that runs between request and response in a server.

It can:

  • Modify request/response
  • Execute logic
  • Pass control to next middleware

Commonly used in frameworks like Express.js

Example:

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

app.use((req, res, next) => {
console.log("Middleware executed");
next();
});

app.get('/', (req, res) => {
res.send("Hello");
});

app.listen(3000);

61. What is Express.js?

Express.js is a minimal and flexible web framework for Node.js used to build web applications and APIs.

Key features:

  • Simplifies server creation
  • Routing support
  • Middleware support
  • Fast and lightweight

Example:

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

app.get('/', (req, res) => {
res.send("Hello from Express");
});

app.listen(3000);

62. Difference between Node.js and Angular

Node.js vs Angular

FeatureNode.jsAngular
TypeRuntime environmentFrontend framework
UsageBackendFrontend
LanguageJavaScriptTypeScript
Runs onServerBrowser
PurposeBuild APIs, serversBuild UI

63. Difference between frontend and backend development

FrontendBackend
User interfaceServer logic
Runs in browserRuns on server
Technologies: HTML, CSS, JSNode.js, Java, Python
Focus: UI/UXFocus: data & logic

Example:

  • Frontend → Button click
  • Backend → Process request and return data

64. What is routing in Express.js?

Routing refers to handling different HTTP requests at different URLs (endpoints).

Example:

app.get('/', (req, res) => {
res.send("Home");
});

app.post('/user', (req, res) => {
res.send("User created");
});

Explanation:

  • / → handled by GET
  • /user → handled by POST

65. What are environment variables?

Environment variables are external configuration values used to control application behavior without changing code.

Examples:

  • Port number
  • Database URL
  • API keys

66. How do you use process.env?

process.env is an object in Node.js that stores environment variables.

Example:

console.log(process.env.PORT);

Using a default value:

const port = process.env.PORT || 3000;

67. What is NODE_ENV?

NODE_ENV is a special environment variable used to define the environment mode of the application.

Common values:

  • development
  • production
  • test

Usage:

if (process.env.NODE_ENV === "production") {
console.log("Running in production");
}

68. What is REPL?

REPL stands for:

  • Read
  • Evaluate
  • Print
  • Loop

It is an interactive shell in Node.js used to execute JavaScript code line by line.

Start REPL:

node

69. What happens when you run node index.js?

When you run:

node index.js

Steps internally:

  1. Node.js starts runtime
  2. Loads the file
  3. Wraps code inside a function (module wrapper)
  4. Executes code
  5. Event loop starts (if async tasks exist)

70. Difference between __dirname and process.cwd()

__dirnameprocess.cwd()
Directory of current fileCurrent working directory
FixedCan change
Based on file locationBased on where command is run

Example:

console.log(__dirname);
console.log(process.cwd());

71. How do you debug a Node.js application?

Methods:

  1. Console debugging
console.log("Debug info");
  1. Built-in debugger
node inspect app.js
  1. Using Chrome DevTools
node --inspect app.js
  1. Using IDE (VS Code)
  • Breakpoints
  • Step execution
  • Variable inspection

72. How do you execute JavaScript code from a file?

Use the Node.js command:

node filename.js

Example:

node app.js

This runs the JavaScript file using the Node.js runtime.