1. What is Node.js and where can you use it?
Difficulty: EasyType: SubjectiveTopic: Node Basics
Node.js is an open-source, cross-platform JavaScript runtime environment built on Chrome’s V8 engine. It allows running JavaScript on the server side instead of just in the browser. It is commonly used for building web servers, APIs, streaming applications, and real-time apps like chat or online games.
2. Why use Node.js?
Difficulty: EasyType: SubjectiveTopic: Node Basics
Node.js is fast, lightweight, and highly scalable. It supports asynchronous non-blocking operations, making it perfect for real-time and I/O-heavy applications. It uses a single-threaded event loop model, reducing overhead and improving performance.
3. How does Node.js work?
Difficulty: MediumType: SubjectiveTopic: Node Architecture
Node.js uses an event-driven, non-blocking I/O model. Incoming client requests go into an Event Queue, and the Event Loop processes them. Simple tasks run directly; complex or blocking tasks are handled by background threads in a thread pool. Once completed, results are sent back via callbacks or Promises.
4. Why is Node.js single-threaded?
Difficulty: MediumType: SubjectiveTopic: Concurrency Model
Node.js uses a single thread to handle requests asynchronously. This approach prevents the overhead of managing multiple threads and allows it to scale efficiently with minimal memory usage through event-driven I/O operations.
5. If Node.js is single-threaded, how does it handle concurrency?
Difficulty: MediumType: SubjectiveTopic: Concurrency Model
Node.js handles concurrency via its Event Loop and Worker Pool. The Event Loop continuously listens for new events, while the Worker Pool executes I/O or CPU-intensive operations in the background without blocking the main thread.
6. Explain callback in Node.js.
Difficulty: MediumType: SubjectiveTopic: Callbacks
A callback is a function passed as an argument to another function, executed once a task completes. It prevents blocking operations and allows asynchronous execution. However, deeply nested callbacks can lead to 'callback hell'.
Example Code
fs.readFile('file.txt', (err, data) => { if (err) throw err; console.log(data.toString()); });7. What are the advantages of using promises instead of callbacks?
Difficulty: MediumType: SubjectiveTopic: Promises
Promises simplify asynchronous flow by chaining operations with `.then()` and handling errors with `.catch()`. They avoid nested callbacks, improve readability, and allow better error propagation.
8. How would you define the term I/O?
Difficulty: EasyType: SubjectiveTopic: I/O Basics
I/O (Input/Output) refers to data transfer between a system and external resources like files, networks, or devices. Node.js optimizes I/O using non-blocking event-driven architecture to handle many concurrent operations efficiently.
9. How is Node.js most frequently used?
Difficulty: EasyType: SubjectiveTopic: Node Basics
Node.js is used for real-time chat apps, streaming platforms, IoT systems, single-page applications, APIs, and microservices due to its scalability and event-driven nature.
10. Explain the difference between frontend and backend development.
Difficulty: EasyType: SubjectiveTopic: Backend Basics
Frontend (client-side) involves what users see and interact with—HTML, CSS, JavaScript, React, etc. Backend (server-side) handles data, APIs, and server logic using languages like Node.js, Python, or Java.
11. What is NPM?
Difficulty: EasyType: SubjectiveTopic: NPM
NPM (Node Package Manager) manages packages for Node.js. It provides an online registry for open-source modules and a CLI tool to install, update, or remove packages.
Example Code
npm install express
12. What are the modules in Node.js?
Difficulty: MediumType: SubjectiveTopic: Modules
Modules are reusable JavaScript files that export specific functionality. Node.js includes built-in core modules like `fs`, `http`, `url`, and `stream`. Developers can also create custom modules using `module.exports`.
Example Code
const fs = require('fs');
const data = fs.readFileSync('file.txt');13. What is the purpose of module.exports?
Difficulty: MediumType: SubjectiveTopic: Modules
module.exports defines what values or functions a module exposes to other files. It allows encapsulation and reusability of code across different parts of an application.
Example Code
// math.js
module.exports.add = (a,b)=>a+b;
// app.js
const math=require('./math');
console.log(math.add(2,3));14. Why is Node.js preferred over other backend technologies like Java or PHP?
Difficulty: MediumType: SubjectiveTopic: Node Comparison
Node.js is faster, supports asynchronous I/O, and allows using JavaScript both on frontend and backend. It’s lightweight, scalable, and ideal for data-intensive applications. In contrast, Java/PHP rely on multi-threaded blocking architectures.
15. What does event-driven programming mean in Node.js?
Difficulty: MediumType: SubjectiveTopic: Events API
Event-driven programming means the flow of the program is determined by events such as user actions or messages from other programs. In Node.js, events trigger callback functions through the EventEmitter system, allowing non-blocking, asynchronous behavior.
16. What is an Event Loop in Node.js?
Difficulty: MediumType: SubjectiveTopic: Event Loop
The Event Loop is the core of Node.js’s asynchronous architecture. It continuously checks the event queue and executes callbacks or promises when their operations complete. It allows Node.js to handle thousands of requests on a single thread.
17. Differentiate between process.nextTick() and setImmediate().
Difficulty: MediumType: SubjectiveTopic: Event Loop
process.nextTick() executes a callback immediately after the current operation, before the next event loop iteration. setImmediate() schedules the callback for the next iteration of the event loop, after I/O events. nextTick() runs sooner.
Example Code
process.nextTick(()=>console.log('Next Tick'));
setImmediate(()=>console.log('Immediate'));18. What is an EventEmitter in Node.js?
Difficulty: MediumType: SubjectiveTopic: Events API
EventEmitter is a core module that allows objects to emit and listen for events. It forms the base for asynchronous communication in Node.js. You can register listeners with `.on()` and trigger them with `.emit()`.
Example Code
const EventEmitter=require('events');
const emitter=new EventEmitter();
emitter.on('greet',()=>console.log('Hello!'));
emitter.emit('greet');19. What are the two types of API functions in Node.js?
Difficulty: EasyType: SubjectiveTopic: API Design
Node.js provides asynchronous (non-blocking) and synchronous (blocking) APIs. Asynchronous APIs allow other code to execute while waiting for results, whereas synchronous APIs block the event loop until completion.
20. What is the package.json file?
Difficulty: EasyType: SubjectiveTopic: Package.json
package.json holds project metadata like name, version, dependencies, and scripts. It is created using `npm init` and allows npm to install and manage required packages for your project.
Example Code
{ "name": "my-app", "dependencies": { "express": "^4.18.0" } }21. How would you use the URL module in Node.js?
Difficulty: MediumType: SubjectiveTopic: URL API
The URL module helps parse, resolve, and format URLs. It splits a web address into parts like hostname, path, and query parameters, making it easy to work with HTTP requests.
Example Code
const url=require('url');
const q=url.parse('https://example.com/home?id=10',true);
console.log(q.host, q.query.id);22. What is Express.js?
Difficulty: MediumType: SubjectiveTopic: Express Basics
Express.js is a minimal and flexible web framework built on Node.js. It simplifies handling routes, requests, and middleware to build RESTful APIs and web apps quickly.
23. How do you create a simple Express.js application?
Difficulty: MediumType: SubjectiveTopic: Express Basics
First, import Express, create an app using `express()`, define routes, and start listening on a port. Express automatically handles HTTP requests and responses.
Example Code
const express=require('express');
const app=express();
app.get('/',(req,res)=>res.send('Hello World'));
app.listen(3000);24. What are streams in Node.js?
Difficulty: MediumType: SubjectiveTopic: Streams
Streams are objects that let you read or write data continuously. There are four types: Readable, Writable, Duplex, and Transform. They make data handling efficient, especially for large files.
Example Code
const fs=require('fs');
fs.createReadStream('input.txt').pipe(fs.createWriteStream('output.txt'));25. How do you install, update, and delete a dependency?
Difficulty: EasyType: SubjectiveTopic: Package Mgmt
Use `npm install package-name` to add, `npm update package-name` to update, and `npm uninstall package-name` to remove a dependency.
Example Code
npm install express
npm update express
npm uninstall express
26. How do you create a simple server in Node.js that returns Hello World?
Difficulty: EasyType: SubjectiveTopic: Express Basics
Use the HTTP module, call `createServer()` with a callback that handles requests and responses, and listen on a port.
Example Code
const http=require('http');
http.createServer((req,res)=>{
res.write('Hello World');
res.end();
}).listen(8080);27. Explain asynchronous and non-blocking APIs in Node.js.
Difficulty: MediumType: SubjectiveTopic: Async Patterns
All Node.js APIs are asynchronous, meaning they don’t block execution. The server can process other requests while waiting for one operation to finish. Results are handled using callbacks, promises, or async/await.
28. How do we implement async in Node.js?
Difficulty: MediumType: SubjectiveTopic: Async Patterns
You can write async functions using `async` and `await`. The function waits for a Promise to resolve before executing the next line, making async code easy to read and debug.
Example Code
async function getData(){
const res=await fetch('https://api.com');
const data=await res.json();
console.log(data);
}29. What is REPL in Node.js?
Difficulty: EasyType: SubjectiveTopic: REPL
REPL stands for Read-Eval-Print Loop. It is a Node.js command-line tool that allows developers to quickly test code snippets. You can type JavaScript directly into the terminal, and Node.js will execute and return results immediately — useful for debugging and experimenting.
30. What is the control flow function in Node.js?
Difficulty: MediumType: SubjectiveTopic: Async Control
A control flow function manages the order in which asynchronous functions are executed. It ensures that dependent functions wait for the previous ones to finish before running, avoiding messy callback chains.
31. How does control flow manage function calls?
Difficulty: MediumType: SubjectiveTopic: JS Functions
Control flow manages async function calls by defining clear execution order. It executes one function, waits for its callback or promise, and then triggers the next one. Libraries like `async` simplify this with series or parallel task control.
32. What is the difference between fork() and spawn() in Node.js?
Difficulty: MediumType: SubjectiveTopic: Child Process
Both create new processes. `spawn()` launches a new process with a given command. `fork()` is a special case of `spawn()` that creates a new Node.js instance for parallel execution, ideal for running multiple workers.
Example Code
const { fork, spawn } = require('child_process');
const child = fork('worker.js'); // new Node process
const run = spawn('ls', ['-lh']); // system command33. What is the Buffer class in Node.js?
Difficulty: MediumType: SubjectiveTopic: Buffers
The Buffer class is used to handle binary data directly, especially in file streams or TCP connections. Buffers are similar to arrays of integers but represent raw memory. This allows efficient reading and writing of binary data.
Example Code
const buf = Buffer.from('Hello');
console.log(buf.toString());34. What is piping in Node.js?
Difficulty: MediumType: SubjectiveTopic: Streams
Piping connects the output of one stream directly into another stream, commonly used to transfer data efficiently between files or network responses. It eliminates manual data handling.
Example Code
const fs = require('fs');
fs.createReadStream('input.txt').pipe(fs.createWriteStream('output.txt'));35. How do you open a file in Node.js?
Difficulty: MediumType: SubjectiveTopic: File System
Use the `fs.open()` method to open a file. It takes a filename, flag (like 'r' for read or 'w' for write), and a callback. Always handle errors to avoid crashes.
Example Code
const fs = require('fs');
fs.open('example.txt', 'r', (err, fd) => {
if (err) throw err;
console.log('File opened successfully');
});36. What are some of the flags used in file read/write operations?
Difficulty: EasyType: SubjectiveTopic: File System
Common file system flags include: 'r' for read, 'w' for write, 'a' for append, 'r+' for read/write, and 'wx' for write only if the file doesn’t already exist.
37. What is callback hell?
Difficulty: MediumType: SubjectiveTopic: Callbacks
Callback hell occurs when multiple asynchronous functions are nested within each other, creating deep and unreadable code. It can be solved by using Promises or async/await for cleaner control flow.
Example Code
// Callback Hell Example
fs.readFile('a.txt', () => {
fs.readFile('b.txt', () => {
fs.readFile('c.txt', () => {
console.log('done');
});
});
});38. What is a Reactor Pattern in Node.js?
Difficulty: MediumType: SubjectiveTopic: Runtime Internals
The Reactor Pattern is the design model behind Node.js’s non-blocking I/O system. It uses an event demultiplexer that listens for events and dispatches them to handlers asynchronously, improving performance and scalability.
39. What is a Test Pyramid in Node.js?
Difficulty: MediumType: SubjectiveTopic: Testing
The Test Pyramid represents the ideal balance of test types: more unit tests at the bottom, fewer integration tests in the middle, and even fewer end-to-end tests at the top. It ensures faster, stable, and maintainable testing strategies.
40. Why does Node.js use the Google V8 engine?
Difficulty: MediumType: SubjectiveTopic: Runtime Internals
Node.js uses Google’s V8 engine because it compiles JavaScript directly into machine code for high performance. It supports just-in-time (JIT) compilation, making Node.js fast and efficient for both server and network operations.
41. Explain the concept of middleware in Node.js.
Difficulty: MediumType: SubjectiveTopic: Middleware
Middleware functions in Node.js (especially in Express) process incoming requests before they reach route handlers. They can modify requests, add headers, handle authentication, or terminate the request-response cycle.
Example Code
app.use((req,res,next)=>{
console.log('Request Time:', Date.now());
next();
});42. What are the different types of HTTP requests in Node.js?
Difficulty: EasyType: SubjectiveTopic: HTTP Basics
Common HTTP request methods include: GET (retrieve data), POST (create or modify), PUT (update), DELETE (remove), and PATCH (partial update). Node’s `http` and Express frameworks support them all.
43. How would you connect a MongoDB database to Node.js?
Difficulty: MediumType: SubjectiveTopic: Databases
To connect MongoDB with Node.js, use the official MongoDB driver or Mongoose. You create a client using MongoClient, provide the connection URL, and call `connect()`. Mongoose adds schema and validation features.
Example Code
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
await client.connect();
console.log('Connected to MongoDB');44. What is the purpose of NODE_ENV in Node.js?
Difficulty: EasyType: SubjectiveTopic: Environment
NODE_ENV is an environment variable that defines the runtime mode of your app, such as 'development', 'production', or 'test'. It helps configure logging, caching, and debugging behaviors accordingly.
Example Code
if(process.env.NODE_ENV==='production'){console.log('Running in production');}45. List various timing features available in Node.js.
Difficulty: EasyType: SubjectiveTopic: Timers
Node.js provides global timing functions like `setTimeout`, `setInterval`, `setImmediate`, and `process.nextTick`. These schedule functions at different stages of the event loop for asynchronous control.
Example Code
setTimeout(()=>console.log('Timeout'),1000);
setImmediate(()=>console.log('Immediate'));
process.nextTick(()=>console.log('Next Tick'));46. What is WASI and why is it introduced in Node.js?
Difficulty: MediumType: SubjectiveTopic: Runtime APIs
WASI (WebAssembly System Interface) allows WebAssembly modules to run in non-browser environments like Node.js. It provides sandboxed access to files and environment variables for better security and performance.
47. What are first-class functions in JavaScript?
Difficulty: EasyType: SubjectiveTopic: JS Functions
First-class functions are functions that can be stored in variables, passed as arguments, or returned from other functions. Node.js uses this concept extensively for callbacks and asynchronous handling.
Example Code
function greet(){return 'Hello';}
function run(fn){console.log(fn());}
run(greet);48. How do you manage packages in a Node.js project?
Difficulty: MediumType: SubjectiveTopic: Package Mgmt
Node.js uses npm or yarn for package management. You can install third-party modules, manage dependencies via package.json, and use scripts for automation. `npm install` reads dependencies and installs them automatically.
Example Code
npm install express
npm list --depth=0
49. How is Node.js better than other frameworks?
Difficulty: EasyType: SubjectiveTopic: Node Basics
Node.js is fast, scalable, and event-driven. It handles many concurrent connections using non-blocking I/O, making it ideal for real-time applications. Its single-threaded model with the V8 engine ensures efficiency.
50. What is a fork in Node.js?
Difficulty: MediumType: SubjectiveTopic: Child Process
The `fork()` method in the child_process module creates a new Node.js process that runs a separate script. It’s useful for scaling CPU-bound tasks or running isolated background jobs.
Example Code
const { fork } = require('child_process');
const worker = fork('worker.js');
worker.on('message', msg => console.log('Message:', msg));51. List the two arguments that async.queue() takes as input.
Difficulty: MediumType: SubjectiveTopic: Async Control
The async.queue() function takes a worker function (that processes tasks) and an optional concurrency limit. It allows you to process multiple tasks in parallel while controlling concurrency.
52. What is the purpose of module.exports in Node.js?
Difficulty: EasyType: SubjectiveTopic: Modules
module.exports allows functions, objects, or values to be shared between files. It’s used with require() to import exported members into other modules.
Example Code
// math.js
module.exports.add=(a,b)=>a+b;
// app.js
const { add }=require('./math');
console.log(add(2,3));53. What tools ensure consistent code style in Node.js?
Difficulty: EasyType: SubjectiveTopic: Code Quality
Tools like ESLint and Prettier enforce consistent formatting and code quality. They integrate with editors and CI pipelines to prevent syntax errors and maintain readable codebases.
54. What is the difference between asynchronous and synchronous functions in Node.js?
Difficulty: MediumType: SubjectiveTopic: Async Patterns
Synchronous functions block further code execution until completion. Asynchronous functions run in the background and use callbacks, promises, or async/await, allowing Node.js to handle many operations efficiently.
Example Code
// Sync
const fs=require('fs');
fs.readFileSync('file.txt');
// Async
fs.readFile('file.txt',()=>console.log('Done'));55. How does Node.js overcome the problem of blocking I/O operations?
Difficulty: MediumType: SubjectiveTopic: Concurrency Model
Node.js uses non-blocking asynchronous I/O and an event-driven architecture. Instead of waiting for tasks like file reads or database calls, it delegates them to the event loop and continues executing other code.
56. How can you use async/await in Node.js?
Difficulty: MediumType: SubjectiveTopic: Async Await
You mark a function as async and use await to pause execution until a promise resolves. This makes asynchronous code look synchronous, improving readability and error handling.
Example Code
async function loadData(){
try{
const res=await fetch('https://api.com');
const data=await res.json();
console.log(data);
}catch(err){console.error(err);}
}57. Why should you separate the Express app and the server?
Difficulty: MediumType: SubjectiveTopic: App Structure
Separating your app from the server simplifies testing, scaling, and deployment. The app handles routes and middleware, while the server handles network configuration and listening. This structure improves maintainability.
58. What is Libuv and why is it important in Node.js?
Difficulty: MediumType: SubjectiveTopic: Runtime Internals
Libuv is the C library that powers Node.js’s event loop and asynchronous I/O operations. It handles non-blocking file I/O, DNS, and network operations across different operating systems, enabling Node to stay single-threaded yet highly concurrent.
59. What are global objects in Node.js?
Difficulty: EasyType: SubjectiveTopic: Globals
Global objects are accessible anywhere in Node.js without importing them. Examples include `process`, `console`, `Buffer`, `__dirname`, and `setTimeout`. These objects provide environment info, logging, and system-level access.
60. Why is the assert module used in Node.js?
Difficulty: EasyType: SubjectiveTopic: Core Modules
The assert module helps test conditions in code. It throws errors if an expression evaluates to false, making it useful for debugging and creating unit tests in Node.js.
Example Code
const assert = require('assert');
assert.strictEqual(2 + 2, 4);61. Why is Express.js commonly used in Node.js projects?
Difficulty: EasyType: SubjectiveTopic: Express Basics
Express simplifies HTTP server creation and routing. It handles requests, middleware, and responses easily, making it ideal for APIs and full-stack apps. It’s fast, minimal, and widely supported.
62. What is the use of the connect module in Node.js?
Difficulty: MediumType: SubjectiveTopic: Middleware
The connect module provides a middleware framework for handling HTTP requests. It’s the foundation of Express. Developers can plug in middleware for cookies, sessions, authentication, and error handling.
Example Code
const connect = require('connect');
const app = connect();
app.use((req,res)=>{res.end('Hello Connect');});
app.listen(3000);63. What are LTS releases of Node.js?
Difficulty: EasyType: SubjectiveTopic: Releases
LTS stands for Long-Term Support. These Node.js versions receive stability, security, and bug fixes for about 30 months, making them suitable for production environments.
64. What is ESLint used for in Node.js?
Difficulty: EasyType: SubjectiveTopic: Code Quality
ESLint is a static code analysis tool that identifies syntax issues, enforces coding standards, and improves code quality. It helps keep a consistent style and catches bugs early.
65. How does Node.js handle child threads?
Difficulty: MediumType: SubjectiveTopic: Worker Threads
Node.js runs JavaScript on a single thread but can create child processes using `child_process` or worker threads. These allow parallel execution without blocking the event loop.
Example Code
const { Worker } = require('worker_threads');
new Worker('./task.js');66. How can clustering enhance Node.js performance?
Difficulty: MediumType: SubjectiveTopic: Clustering
Clustering lets Node.js utilize multiple CPU cores. It spawns multiple worker processes sharing the same server port. This improves throughput and handles higher concurrent loads efficiently.
Example Code
const cluster=require('cluster');
const http=require('http');
if(cluster.isPrimary){for(let i=0;i<4;i++)cluster.fork();}
else{http.createServer((req,res)=>res.end('Hello')).listen(3000);}67. What is a thread pool, and which library handles it in Node.js?
Difficulty: MediumType: SubjectiveTopic: Worker Threads
A thread pool is a collection of background threads used for heavy I/O operations like file access and compression. Node.js uses the libuv library to manage this pool and distribute tasks efficiently.
68. How are worker threads different from clusters?
Difficulty: MediumType: SubjectiveTopic: Worker Threads
Clusters create multiple Node.js processes, each running on a CPU core. Worker threads, however, share memory within a single process. Workers are better for CPU-intensive tasks; clusters are ideal for scaling web servers.
69. How can you measure the duration of async operations in Node.js?
Difficulty: MediumType: SubjectiveTopic: Timers
You can use console.time/console.timeEnd or performance.now() to measure how long async operations take. These tools help track performance bottlenecks in APIs or I/O-heavy code.
Example Code
console.time('fetch');
await fetch('https://api.com');
console.timeEnd('fetch');70. What is tracing in Node.js?
Difficulty: MediumType: SubjectiveTopic: Observability
Tracing collects information about function calls and system events to analyze performance. Node.js’s built-in tracing API and tools like Chrome DevTools help identify bottlenecks and optimize runtime behavior.
71. What is the use of the crypto module in Node.js?
Difficulty: MediumType: SubjectiveTopic: Crypto API
The crypto module enables secure data encryption, hashing, and signing. It supports algorithms like AES, RSA, and SHA, helping developers secure passwords, tokens, and sensitive data.
Example Code
const crypto=require('crypto');
const hash=crypto.createHash('sha256').update('secret').digest('hex');
console.log(hash);72. What are the different types of HTTP requests supported in Node.js?
Difficulty: EasyType: SubjectiveTopic: HTTP Basics
Node.js supports all standard HTTP request methods such as GET (fetch data), POST (create data), PUT (update data), DELETE (remove data), PATCH (partial update), and HEAD (metadata only). These can be implemented using the `http` or `express` modules.
Example Code
app.get('/users',(req,res)=>res.send('List'));
app.post('/users',(req,res)=>res.send('Created'));73. How do you connect MongoDB with Node.js?
Difficulty: MediumType: SubjectiveTopic: Databases
MongoDB connects through the official driver or Mongoose. The `connect()` function establishes a persistent connection, and once connected, it can perform CRUD operations efficiently.
Example Code
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb');74. What is NODE_ENV and why is it important?
Difficulty: EasyType: SubjectiveTopic: Environment
NODE_ENV defines the environment in which the app runs — 'development', 'test', or 'production'. It controls configuration like logging, performance optimization, and debug settings. Production mode improves speed and disables verbose logs.
75. How does the DNS lookup function work in Node.js?
Difficulty: MediumType: SubjectiveTopic: DNS Module
The `dns.lookup()` method converts domain names into IP addresses. It’s part of Node’s built-in `dns` module and is used internally by HTTP requests to resolve hostnames before making connections.
Example Code
const dns=require('dns');
dns.lookup('google.com',(err,address)=>console.log(address));76. How do you enable HTTPS in Node.js?
Difficulty: MediumType: SubjectiveTopic: TLS Security
Node’s `https` module lets you create secure servers using SSL/TLS certificates. HTTPS ensures encrypted communication between clients and servers, preventing eavesdropping and data tampering.
Example Code
const https=require('https');
const fs=require('fs');
const opts={key:fs.readFileSync('key.pem'),cert:fs.readFileSync('cert.pem')};
https.createServer(opts,(req,res)=>res.end('Secure!')).listen(443);77. What are the main security implementations present in Node.js?
Difficulty: MediumType: SubjectiveTopic: API Security
Node.js implements sandboxing to isolate code, uses TLS/SSL for encryption, environment variables for secrets, and libraries like Helmet for securing HTTP headers. Regular dependency audits also prevent known vulnerabilities.
78. What is Passport in Node.js and what is it used for?
Difficulty: MediumType: SubjectiveTopic: Auth
Passport.js is a flexible authentication middleware for Node.js. It supports local logins and social logins (Google, Facebook, GitHub). It simplifies user authentication by using modular strategies.
Example Code
const passport=require('passport');
app.post('/login',passport.authenticate('local'),(req,res)=>res.send('Logged in'));79. What is Punycode in Node.js?
Difficulty: MediumType: SubjectiveTopic: Core Modules
Punycode converts Unicode domain names (like emoji or non-English characters) into ASCII format for DNS compatibility. Node.js includes the Punycode module for backward compatibility with international domains.
Example Code
const punycode=require('punycode/');
console.log(punycode.encode('mañana'));80. Does Node.js provide a built-in debugger?
Difficulty: MediumType: SubjectiveTopic: Debugging
Yes. You can run `node inspect app.js` to debug applications. The built-in debugger allows step-by-step execution, variable inspection, and breakpoints using Chrome DevTools or VSCode integration.
Example Code
node inspect index.js
// open chrome://inspect for debugging
81. What is the difference between readFile and createReadStream?
Difficulty: MediumType: SubjectiveTopic: Streams
`fs.readFile()` reads the entire file into memory before processing, making it suitable for small files. `fs.createReadStream()` reads chunks of data as streams, ideal for large files or real-time data transfer.
Example Code
fs.createReadStream('large.txt').pipe(fs.createWriteStream('copy.txt'));82. How do you get information about a file in Node.js?
Difficulty: EasyType: SubjectiveTopic: File System
Use `fs.stat()` to get metadata like size, creation date, and modification time. It’s asynchronous and part of the core `fs` module.
Example Code
const fs=require('fs');
fs.stat('file.txt',(err,stats)=>console.log(stats.size));83. How does TLS/SSL encryption improve Node.js security?
Difficulty: MediumType: SubjectiveTopic: TLS Security
TLS (Transport Layer Security) encrypts data between client and server, preventing eavesdropping and tampering. Node’s `https` and `tls` modules enable secure communication using certificates.
84. Explain how error handling works in Node.js applications.
Difficulty: MediumType: SubjectiveTopic: Error Handling
Node.js uses try-catch for synchronous errors and callback or Promise rejection handlers for async code. Uncaught errors crash the process, so using centralized error middleware or process event handlers (`process.on('uncaughtException')`) ensures graceful recovery.
Example Code
app.use((err,req,res,next)=>{
console.error(err.stack);
res.status(500).send('Something broke!');
});85. How do you handle errors in asynchronous code using async/await?
Difficulty: MediumType: SubjectiveTopic: Error Handling
You can wrap asynchronous code in a try-catch block or use middleware that automatically catches rejections. For production apps, centralized handlers prevent crashes and maintain clean logs.
Example Code
try {
const data = await getData();
} catch (err) {
console.error('Error fetching data', err);
}86. How can logging improve debugging and monitoring in Node.js?
Difficulty: MediumType: SubjectiveTopic: Observability
Logging helps track app behavior and diagnose problems. Libraries like Winston or Pino provide log levels (info, warn, error) and can output structured JSON for log management systems like Datadog or CloudWatch.
Example Code
const winston = require('winston');
const logger = winston.createLogger({ level:'info', transports:[ new winston.transports.Console() ] });
logger.info('Server started');87. How do you manage environment variables in Node.js?
Difficulty: MediumType: SubjectiveTopic: Environment
Environment variables store secrets like API keys and database URLs. You can use `process.env` or a library like dotenv to load them from a .env file. Never hardcode secrets in code.
Example Code
require('dotenv').config();
const dbUrl = process.env.DATABASE_URL;88. How do you write and run tests using Mocha?
Difficulty: MediumType: SubjectiveTopic: Testing
Mocha is a JavaScript test framework that runs in Node.js and browsers. Tests are written using describe/it blocks and assertions from Chai or Assert. Run with `npx mocha` or configure in npm scripts.
Example Code
const assert=require('assert');
describe('Array',()=>{
it('should return -1 when value not found',()=>{
assert.equal([1,2,3].indexOf(4),-1);
});
});89. Why is Jest popular for testing Node.js apps?
Difficulty: MediumType: SubjectiveTopic: Testing
Jest provides zero-configuration testing with built-in mocks, snapshot testing, and parallel execution. It’s widely used for both backend and frontend testing in JavaScript projects.
Example Code
test('adds 2 + 2',()=>{
expect(2+2).toBe(4);
});90. What is the Test Pyramid and how does it apply to Node.js APIs?
Difficulty: MediumType: SubjectiveTopic: Testing
The Test Pyramid recommends writing many small unit tests, fewer integration tests, and very few end-to-end tests. For Node.js APIs, test each function (unit), routes with databases (integration), and full flows (E2E).
91. What is Continuous Integration (CI) and how does it benefit Node.js projects?
Difficulty: MediumType: SubjectiveTopic: DevOps
CI automatically runs tests and linting whenever you push code. Tools like GitHub Actions or Jenkins ensure consistent quality, catch bugs early, and simplify deployment pipelines.
92. How do you deploy a Node.js application to production?
Difficulty: MediumType: SubjectiveTopic: Deployment
Node.js apps can be deployed using PM2, Docker, or cloud platforms like AWS, Vercel, and Heroku. The process includes building the app, setting environment variables, and using a reverse proxy like Nginx for routing.
Example Code
pm2 start app.js --name myapp
pm2 logs myapp
93. How can PM2 improve Node.js deployment?
Difficulty: MediumType: SubjectiveTopic: Clustering
PM2 manages Node.js processes, restarts apps on crashes, and supports cluster mode for multi-core scaling. It simplifies logging, monitoring, and zero-downtime deployments.
Example Code
pm2 start app.js -i max
pm2 monit
94. How can you measure performance in a Node.js app?
Difficulty: MediumType: SubjectiveTopic: Performance
You can measure performance using tools like `clinic.js`, Node’s `--prof` flag, or APM tools (Datadog, New Relic). Benchmark code using console.time() or the Performance API to detect slow functions.
95. How can static analysis tools improve Node.js quality?
Difficulty: MediumType: SubjectiveTopic: Code Quality
Static analysis tools like ESLint and TypeScript detect errors before runtime. They help enforce coding standards and reduce defects through early feedback during development.
96. How do you handle graceful shutdown in Node.js?
Difficulty: MediumType: SubjectiveTopic: Shutdown
Graceful shutdown ensures open connections and background tasks finish before exiting. You can listen for signals like SIGINT or SIGTERM and close servers cleanly.
Example Code
process.on('SIGINT',()=>{
server.close(()=>{
console.log('Server closed gracefully');
process.exit(0);
});
});97. What is a CI/CD pipeline and why is it essential?
Difficulty: MediumType: SubjectiveTopic: DevOps
CI/CD automates testing, building, and deployment. CI ensures code integrity, while CD automates releases to production. Together, they reduce manual errors and accelerate delivery.
98. How can you optimize API performance in Node.js applications?
Difficulty: MediumType: SubjectiveTopic: API Performance
Use caching (Redis or in-memory), pagination, compression, connection pooling, and asynchronous code. Avoid blocking calls, use async/await efficiently, and enable GZIP compression for responses. Profiling tools like Clinic.js help spot slow endpoints.
99. What are common caching strategies used in Node.js?
Difficulty: MediumType: SubjectiveTopic: Caching
Common strategies include in-memory cache (Node-cache), distributed cache (Redis), and HTTP-level caching using ETags or Cache-Control headers. Caching reduces repeated database hits and speeds up response times.
Example Code
const cache=new Map();
function getUser(id){
if(cache.has(id)) return cache.get(id);
const user=db.find(id);
cache.set(id,user);
return user;
}100. How can you implement API rate limiting in Node.js?
Difficulty: MediumType: SubjectiveTopic: API Security
Use packages like `express-rate-limit` or Redis-based counters to restrict requests per user or IP. It protects servers from abuse and ensures fair usage.
Example Code
import rateLimit from 'express-rate-limit';
const limiter=rateLimit({windowMs:60000,max:100});
app.use(limiter);101. How does Node.js handle large file streaming efficiently?
Difficulty: MediumType: SubjectiveTopic: Streams
Using streams allows data to be processed in chunks instead of loading the entire file into memory. This improves performance and reduces memory usage, especially for videos or large logs.
Example Code
fs.createReadStream('video.mp4').pipe(res);102. How can you scale a Node.js app across multiple CPU cores?
Difficulty: MediumType: SubjectiveTopic: Clustering
Use the cluster module or PM2 to spawn multiple worker processes. Each worker handles requests independently, improving concurrency and performance.
Example Code
import cluster from 'cluster';
import os from 'os';
if(cluster.isPrimary){os.cpus().forEach(()=>cluster.fork());}103. How can you implement load balancing for Node.js services?
Difficulty: MediumType: SubjectiveTopic: Scaling
Load balancing can be achieved with Nginx, HAProxy, or PM2 cluster mode. It distributes incoming requests evenly across Node.js instances to prevent overload.
104. How do you detect and fix memory leaks in Node.js?
Difficulty: MediumType: SubjectiveTopic: Performance
Use the Chrome DevTools Heap Snapshot or tools like `clinic heapprofiler` to track object growth. Common causes are global variables, unclosed streams, or forgotten timers.
105. What tools can you use for error monitoring in Node.js?
Difficulty: EasyType: SubjectiveTopic: Observability
Popular tools include Sentry, Datadog, and LogRocket. They capture errors, performance traces, and stack info in real-time for debugging and analytics.
106. How do you handle file uploads efficiently in Node.js?
Difficulty: MediumType: SubjectiveTopic: File Uploads
Use `multer` for handling multipart/form-data. Store files on disk, in cloud storage (AWS S3), or streams for real-time processing.
Example Code
import multer from 'multer';
const upload=multer({dest:'uploads/'});
app.post('/upload',upload.single('file'),(req,res)=>res.send('Uploaded'));107. Why is connection pooling important in Node.js?
Difficulty: MediumType: SubjectiveTopic: Databases
Connection pooling reuses existing database connections instead of creating new ones for each request, reducing latency and improving performance under high traffic.
108. What steps can you take to secure a Node.js app?
Difficulty: MediumType: SubjectiveTopic: API Security
Use HTTPS, sanitize input, apply Helmet middleware, rate-limit endpoints, and validate JWTs. Avoid eval(), keep dependencies updated, and store secrets in environment variables.
109. How does JWT authentication work in Node.js?
Difficulty: MediumType: SubjectiveTopic: Auth
JWTs are signed tokens containing user data. The server verifies the token signature to authenticate users. JWTs are stateless and used for scalable authentication across APIs.
Example Code
import jwt from 'jsonwebtoken';
const token = jwt.sign({id:1},'secret',{expiresIn:'1h'});
const decoded = jwt.verify(token,'secret');110. How do you enable GZIP compression in a Node.js app?
Difficulty: EasyType: SubjectiveTopic: Compression
Use the `compression` middleware in Express to reduce response size and speed up content delivery.
Example Code
import compression from 'compression';
app.use(compression());
111. How can Docker improve Node.js deployment?
Difficulty: MediumType: SubjectiveTopic: Scaling
Docker containers isolate app environments and dependencies, ensuring consistent deployments. You can scale containers easily using Docker Compose or Kubernetes.
Example Code
FROM node:18
WORKDIR /app
COPY . .
RUN npm install
CMD ['npm','start']
112. What is REPL in Node.js and what are its components?
Difficulty: EasyType: SubjectiveTopic: REPL
REPL stands for Read–Eval–Print–Loop. It is an interactive shell that executes JavaScript code line by line. It helps developers test and debug quickly.
• Read – reads user input
• Eval – evaluates input
• Print – outputs result
• Loop – waits for new input again.
Example Code
node
> let x = 10; x * 2
20
113. Explain the use of the Timers module in Node.js.
Difficulty: EasyType: SubjectiveTopic: Timers
The Timers module allows scheduling of code execution after a specified time. It provides functions like `setTimeout()`, `setInterval()`, and `setImmediate()` to run callbacks asynchronously in future event loop phases.
Example Code
setTimeout(()=>console.log('After delay'),1000);
setImmediate(()=>console.log('Next phase'));114. What is a Buffer in Node.js and why is it needed?
Difficulty: MediumType: SubjectiveTopic: Buffers
Buffers handle raw binary data in Node.js. They are useful when dealing with file streams, TCP packets, or image data. Buffers are fixed-size byte arrays allocated outside the V8 heap for efficient memory handling.
Example Code
const buf = Buffer.from('Hello');
console.log(buf.toString());115. Explain the util module in Node.js and its common methods.
Difficulty: MediumType: SubjectiveTopic: Core Modules
The util module provides helpful functions for debugging and inheritance. Common methods include `util.inherits()` for classical inheritance, `util.promisify()` to convert callbacks into Promises, and `util.format()` for string formatting.
Example Code
const util=require('util');
const wait=util.promisify(setTimeout);
await wait(1000);116. What is the DNS module and its purpose in Node.js?
Difficulty: MediumType: SubjectiveTopic: DNS Module
The DNS (Domain Name System) module provides methods to resolve domain names to IP addresses. It can perform both asynchronous lookups and direct OS-level resolution using `dns.lookup()` and `dns.resolve()`.
Example Code
const dns=require('dns');
dns.lookup('google.com',(err,addr)=>console.log(addr));117. What is control flow in Node.js and why is it important?
Difficulty: MediumType: SubjectiveTopic: Async Control
Control flow refers to managing asynchronous operations’ order and results. Since Node.js doesn’t block execution, control flow ensures callbacks, promises, and async/await handle dependencies correctly in async code.
118. Explain the Node.js Redis module and its use cases.
Difficulty: MediumType: SubjectiveTopic: Caching
The Redis module allows connecting to Redis servers for caching, message brokering, and session storage. It improves response speed by storing frequent queries in memory instead of querying the database repeatedly.
Example Code
const redis=require('redis');
const client=redis.createClient();
client.set('user','John');119. What are WebSockets and how do they work in Node.js?
Difficulty: MediumType: SubjectiveTopic: WebSockets
WebSockets enable full-duplex (two-way) communication between client and server. They maintain an open connection for real-time updates (e.g., chats, games). Implemented using `ws` or `socket.io` libraries.
Example Code
const WebSocket=require('ws');
const wss=new WebSocket.Server({port:8080});
wss.on('connection',ws=>ws.send('Connected!'));120. What is CORS in Node.js and why is it needed?
Difficulty: MediumType: SubjectiveTopic: CORS
CORS (Cross-Origin Resource Sharing) enables web apps running on one domain to access resources from another. The `cors` npm package sets headers to allow or restrict requests from other origins.
Example Code
const cors=require('cors');
app.use(cors({origin:'*'}));121. Explain the purpose of the TLS module in Node.js.
Difficulty: MediumType: SubjectiveTopic: TLS Security
The TLS module provides SSL/TLS protocols for encrypting data over the network. It’s built on OpenSSL and ensures secure communication between clients and servers.
Example Code
const tls=require('tls');
const server=tls.createServer({key,cert},()=>console.log('TLS Active'));122. How can you read command line arguments in Node.js?
Difficulty: EasyType: SubjectiveTopic: CLI Args
You can use the global `process.argv` array to read CLI arguments passed to the script. Arguments start from index 2, as the first two are node executable and script path.
Example Code
console.log(process.argv.slice(2)); // node app.js arg1 arg2
123. Node.js is built on which JavaScript engine?
Difficulty: EasyType: MCQTopic: Node Basics
- SpiderMonkey
- Chakra
- V8
- Rhino
Node.js uses Google Chrome's V8 engine to compile JavaScript directly into native machine code.
Correct Answer: V8
124. Node.js uses which type of architecture?
Difficulty: EasyType: MCQTopic: Node Architecture
- Multi-threaded blocking
- Single-threaded non-blocking
- Synchronous event-driven
- None of these
Node.js runs on a single thread with an event loop, allowing non-blocking asynchronous operations.
Correct Answer: Single-threaded non-blocking
125. Which command is used to import a module in Node.js?
Difficulty: EasyType: MCQTopic: Modules
- include()
- require()
- import()
- load()
The `require()` function is used to load built-in, third-party, or user-defined modules in Node.js.
Correct Answer: require()
126. What does NPM stand for?
Difficulty: EasyType: MCQTopic: NPM
- Node Project Manager
- Node Package Manager
- Network Package Manager
- New Project Manager
NPM manages Node.js packages and dependencies.
Correct Answer: Node Package Manager
127. Which module is used for file operations in Node.js?
Difficulty: MediumType: MCQTopic: File System
The `fs` module handles file reading, writing, and streaming in Node.js.
Correct Answer: fs
128. Which method in the HTTP module creates a server?
Difficulty: MediumType: MCQTopic: HTTP Basics
- http.start()
- http.listen()
- http.createServer()
- http.server()
The `http.createServer()` method creates an HTTP server that listens to requests.
Correct Answer: http.createServer()
129. Which of the following is true about Buffers in Node.js?
Difficulty: MediumType: MCQTopic: Buffers
- They handle text data only
- They store binary data
- They are resizable arrays
- They are synchronous structures
Buffers are used for handling binary data streams efficiently in Node.js.
Correct Answer: They store binary data
130. The Event Loop in Node.js handles which type of operations?
Difficulty: MediumType: MCQTopic: Event Loop
- Blocking
- Synchronous
- Asynchronous
- Parallel
The event loop manages non-blocking, asynchronous tasks such as I/O and timers.
Correct Answer: Asynchronous
131. What is the advantage of using asynchronous functions in Node.js?
Difficulty: EasyType: MCQTopic: Async Patterns
- They block the main thread
- They improve performance by handling multiple tasks
- They simplify code
- They reduce concurrency
Asynchronous code allows Node.js to handle many I/O operations simultaneously.
Correct Answer: They improve performance by handling multiple tasks
132. A Promise represents:
Difficulty: MediumType: MCQTopic: Promises
- An immediate value
- A value that will be resolved later
- A synchronous computation
- A callback queue
Promises represent a future value — either resolved, rejected, or pending.
Correct Answer: A value that will be resolved later
133. Which module helps create child processes in Node.js?
Difficulty: MediumType: MCQTopic: Child Process
The `child_process` module allows Node.js to execute system commands and spawn subprocesses.
Correct Answer: child_process
134. What is the purpose of the Cluster module in Node.js?
Difficulty: MediumType: MCQTopic: Clustering
- To manage memory leaks
- To enable multi-core scaling
- To schedule timers
- To run async code faster
The Cluster module allows you to run multiple Node.js instances to utilize multi-core CPUs.
Correct Answer: To enable multi-core scaling
135. Which type of stream is both readable and writable?
Difficulty: MediumType: MCQTopic: Streams
- Readable
- Writable
- Duplex
- Transform
A Duplex stream can both read and write data, like a TCP socket.
Correct Answer: Duplex
136. In Express.js, middleware functions have access to:
Difficulty: MediumType: MCQTopic: Middleware
- Request and Response objects
- Only Request object
- Only Response object
- None
Middleware in Express can modify requests, responses, or call the next middleware function.
Correct Answer: Request and Response objects
137. Which middleware helps prevent common security vulnerabilities?
Difficulty: MediumType: MCQTopic: API Security
- cors
- helmet
- body-parser
- dotenv
Helmet helps secure Express apps by setting HTTP headers to prevent XSS, clickjacking, etc.
Correct Answer: helmet
138. What does CORS stand for?
Difficulty: EasyType: MCQTopic: CORS
- Cross-Origin Resource Sharing
- Cross-Origin Resource Setup
- Client-Origin Response Sharing
- Client-Origin Request System
CORS allows controlled access to resources from a different origin (domain, port, or protocol).
Correct Answer: Cross-Origin Resource Sharing
139. Which environment variable defines the app environment in Node.js?
Difficulty: EasyType: MCQTopic: Environment
- ENV_APP
- APP_ENV
- NODE_ENV
- APP_MODE
NODE_ENV is used to specify whether the app is in development, production, or testing mode.
Correct Answer: NODE_ENV
140. The EventEmitter class belongs to which module?
Difficulty: MediumType: MCQTopic: Events API
The `events` module allows creation of custom event-driven logic in Node.js.
Correct Answer: events
141. What does REPL stand for in Node.js?
Difficulty: EasyType: MCQTopic: REPL
- Run Evaluate Print Loop
- Read Eval Print Loop
- Run Execute Program Loop
- Read Execute Program Logic
REPL is an interactive shell that reads user input, evaluates it, prints output, and loops.
Correct Answer: Read Eval Print Loop
142. Which file defines dependencies and metadata for a Node.js project?
Difficulty: EasyType: MCQTopic: Package.json
- node.config
- package.json
- index.js
- project.json
package.json stores project information, dependencies, version, and scripts.
Correct Answer: package.json
143. Which HTTP method is used to delete a resource?
Difficulty: EasyType: MCQTopic: HTTP Basics
DELETE requests are used to remove specified resources from the server.
Correct Answer: DELETE