Interview Preparation

Practice real interview questions with detailed answers

197 Questions
Easy 43 questions
NODE.JS #1.1
Q1: What is Node.js?
Ans: Node.js is an open-source, cross-platform JavaScript runtime built on Google's V8 engine that allows JavaScript to run outside the browser, commonly used for building server-side applications and command-line tools.
NODE.JS #1.2
Q2: Is Node.js a programming language or a framework?
Ans: Node.js is neither a language nor a framework; it's a runtime environment that executes JavaScript code outside a web browser, providing APIs for file systems, networking, and more.
NODE.JS #1.3
Q3: What is the V8 engine?
Ans: V8 is Google's open-source JavaScript and WebAssembly engine (used in Chrome and Node.js) that compiles JavaScript directly into optimized machine code for fast execution.
NODE.JS #1.4
Q4: What is the difference between Node.js and browser JavaScript?
Ans: Node.js provides server-side APIs like file system access, networking, and process management but lacks browser-specific objects like window and document, while browser JavaScript includes the DOM API but lacks direct filesystem or OS-level access for security reasons.
NODE.JS #1.5
Q5: What is npm?
Ans: npm (Node Package Manager) is the default package manager for Node.js, used to install, publish, and manage JavaScript packages and their dependencies via the npm registry.
NODE.JS #1.6
Q6: What is a package.json file?
Ans: package.json is the manifest file for a Node.js project, containing metadata like the project name, version, dependencies, scripts, and entry point.
Code Example
{
 "name": "my-app",
 "version": "1.0.0",
 "main": "index.js",
 "dependencies": { "express": "^4.18.0" }
}
NODE.JS #1.7
Q7: What is the difference between dependencies and devDependencies in package.json?
Ans: dependencies lists packages required for the application to run in production, while devDependencies lists packages only needed during development, like testing tools or bundlers.
NODE.JS #1.8
Q8: What is the difference between global and local npm package installation?
Ans: A locally installed package (default) is placed in the project's node_modules folder and used only within that project, while a globally installed package (-g flag) is available system-wide as a command-line tool.
Code Example
npm install lodash # local
npm install -g nodemon # global
NODE.JS #1.9
Q9: What is the require() function used for?
Ans: require() is the CommonJS function used to import modules, whether built-in Node.js modules, local files, or installed npm packages.
Code Example
const fs = require('fs');
const myModule = require('./myModule');
NODE.JS #1.10
Q10: How do you export multiple values from a Node.js module?
Ans: In CommonJS, you attach multiple properties to module.exports (or exports); in ES Modules, you use named exports.
Code Example
// CommonJS
module.exports = { add, subtract };
// ES Modules
export { add, subtract };
NODE.JS #1.11
Q11: What are Node.js core (built-in) modules?
Ans: Core modules are built into Node.js and available without installation, such as fs (file system), http, path, os, events, and crypto.
Code Example
const path = require('path');
const http = require('http');
NODE.JS #1.12
Q12: What are __dirname and __filename in Node.js?
Ans: __dirname returns the absolute path of the directory containing the currently executing file, and __filename returns the absolute path of the file itself; both are only available in CommonJS modules.
Code Example
console.log(__dirname);
console.log(__filename);
NODE.JS #1.13
Q13: How do you read environment variables in Node.js?
Ans: Environment variables are accessed through process.env, often combined with a package like dotenv to load variables from a .env file during development.
Code Example
require('dotenv').config();
const apiKey = process.env.API_KEY;
NODE.JS #1.14
Q14: What is a callback function in Node.js?
Ans: A callback is a function passed as an argument to another function, invoked after an asynchronous (or synchronous) operation completes, historically the primary way to handle async code in Node.js.
Code Example
fs.readFile('file.txt', (err, data) => {
 if (err) throw err;
 console.log(data.toString());
});
NODE.JS #1.15
Q15: What is the difference between synchronous and asynchronous code execution in Node.js?
Ans: Synchronous code executes sequentially, blocking further execution until each operation completes, while asynchronous code allows Node.js to continue executing other code while waiting for operations like I/O to complete, improving throughput for I/O-bound workloads.
NODE.JS #1.16
Q16: What is the difference between setTimeout() and setInterval()?
Ans: setTimeout() schedules a function to run once after a specified delay, while setInterval() repeatedly schedules a function to run at fixed intervals until cleared with clearInterval().
Code Example
setTimeout(() => console.log('once'), 1000);
const id = setInterval(() => console.log('repeating'), 1000);
clearInterval(id);
NODE.JS #1.17
Q17: What is the difference between a relative and an absolute module path in require()?
Ans: A relative path (starting with ./ or ../) resolves relative to the requiring file's location, while a bare module name (like 'express') is resolved by searching node_modules directories up the folder tree.
NODE.JS #1.18
Q18: How do you read a file asynchronously in Node.js?
Ans: The fs.readFile() method reads a file's contents asynchronously, accepting a callback (or returning a Promise via fs.promises/fs/promises) that receives the data once reading completes.
Code Example
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
 if (err) throw err;
 console.log(data);
});
NODE.JS #1.19
Q19: What is the difference between fs.readFile() and fs.readFileSync()?
Ans: fs.readFile() performs the read asynchronously and doesn't block the event loop, using a callback for the result, while fs.readFileSync() blocks execution until the file is fully read, returning the data directly.
NODE.JS #1.20
Q20: What is the path module used for in Node.js?
Ans: The path module provides utilities for working with file and directory paths in a cross-platform way, such as path.join(), path.resolve(), path.basename(), and path.extname().
Code Example
const path = require('path');
console.log(path.join('/users', 'tom', 'file.txt'));
NODE.JS #1.21
Q21: How do you create a basic HTTP server in Node.js?
Ans: The built-in http module's createServer() method takes a request handler function and returns a server object that can listen() on a specified port.
Code Example
const http = require('http');
const server = http.createServer((req, res) => {
 res.writeHead(200, { 'Content-Type': 'text/plain' });
 res.end('Hello World');
});
server.listen(3000);
NODE.JS #1.22
Q22: What is Express.js?
Ans: Express is a minimal and flexible Node.js web application framework that simplifies building web servers and APIs, providing routing, middleware support, and template engine integration on top of the core http module.
Code Example
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World'));
app.listen(3000);
NODE.JS #1.23
Q23: How do you handle route parameters in Express?
Ans: Route parameters are defined with a colon prefix in the route path and accessed via req.params in the handler function.
Code Example
app.get('/users/:id', (req, res) => {
 res.send(`User ID: ${req.params.id}`);
});
NODE.JS #1.24
Q24: How do you parse JSON request bodies in Express?
Ans: The built-in express.json() middleware parses incoming requests with a JSON payload and populates req.body with the parsed object.
Code Example
app.use(express.json());
app.post('/users', (req, res) => {
 console.log(req.body);
});
NODE.JS #1.25
Q25: How do you serve static files in Express?
Ans: The built-in express.static() middleware serves static files (like images, CSS, and client-side JS) from a specified directory.
Code Example
app.use(express.static('public'));
NODE.JS #1.26
Q26: What is the difference between req.query, req.params, and req.body in Express?
Ans: req.query holds URL query string parameters, req.params holds named route parameters from the URL path, and req.body holds data sent in the request body (like from a POST request), typically requiring body-parsing middleware.
NODE.JS #1.27
Q27: How do you handle errors in synchronous Node.js code?
Ans: You use a standard try-catch block to catch exceptions thrown during synchronous execution.
Code Example
try {
 JSON.parse(invalidJson);
} catch (err) {
 console.error('Parse error:', err.message);
}
NODE.JS #1.28
Q28: How do you handle errors with Promises?
Ans: You attach a .catch() handler to the Promise chain, which catches any rejection from the Promise itself or any previous .then() callback in the chain.
Code Example
doAsyncTask()
 .then(result => process(result))
 .catch(err => console.error('Failed:', err));
NODE.JS #1.29
Q29: What are npm scripts and how do you run them?
Ans: npm scripts are custom commands defined in the 'scripts' section of package.json, executed using 'npm run ' (or directly for 'start' and 'test').
Code Example
{
 "scripts": {
 "start": "node index.js",
 "test": "jest"
 }
}
// run with: npm start / npm test
NODE.JS #1.30
Q30: What is nodemon and why is it used?
Ans: nodemon is a development utility that automatically restarts a Node.js application whenever file changes are detected in the project directory, speeding up the development feedback loop.
Code Example
npm install -g nodemon
nodemon app.js
NODE.JS #1.31
Q31: What is the difference between var, let, and const in JavaScript?
Ans: var is function-scoped and hoisted with an initial value of undefined, let is block-scoped and hoisted without initialization (temporal dead zone), and const is block-scoped like let but cannot be reassigned after initial assignment.
Code Example
var a = 1;
let b = 2;
const c = 3;
NODE.JS #1.32
Q32: What are template literals in JavaScript?
Ans: Template literals, enclosed in backticks, allow embedded expressions using ${} syntax and support multi-line strings without explicit concatenation.
Code Example
const name = 'World';
console.log(`Hello, ${name}!`);
NODE.JS #1.33
Q33: What is the difference between == and === in JavaScript?
Ans: == compares values after type coercion (loose equality), while === compares both value and type without any coercion (strict equality), which is generally recommended to avoid unexpected behavior.
Code Example
console.log(0 == '0'); // true
console.log(0 === '0'); // false
NODE.JS #1.34
Q34: What is the os module used for in Node.js?
Ans: The os module provides operating system-related utility methods and properties, such as os.platform(), os.cpus(), os.totalmem(), and os.freemem().
Code Example
const os = require('os');
console.log(os.cpus().length);
NODE.JS #1.35
Q35: What is the REPL in Node.js?
Ans: REPL stands for Read-Eval-Print Loop; running 'node' without a filename starts an interactive shell where you can type and immediately execute JavaScript code, useful for quick experimentation.
NODE.JS #1.36
Q36: What is the difference between synchronous and asynchronous versions of fs module methods (naming convention)?
Ans: Synchronous fs methods have a 'Sync' suffix (like fs.readFileSync) and block execution until complete, while their asynchronous counterparts (like fs.readFile) accept a callback or return a Promise (via fs.promises) and don't block the event loop.
NODE.JS #1.37
Q37: What is dotenv and why is it commonly used in Node.js projects?
Ans: dotenv is a zero-dependency npm package that loads environment variables from a .env file into process.env, keeping sensitive configuration (like API keys and database URLs) out of source code and version control.
Code Example
// .env file: API_KEY=abc123
require('dotenv').config();
console.log(process.env.API_KEY);
NODE.JS #1.38
Q38: What is the difference between an HTTP 200, 201, 400, 401, 403, 404, and 500 status code?
Ans: 200 means success (OK), 201 means a resource was successfully created, 400 means bad request (client error), 401 means unauthorized (authentication required), 403 means forbidden (authenticated but not permitted), 404 means resource not found, and 500 means an internal server error occurred.
NODE.JS #1.39
Q39: What is the purpose of a .gitignore file in a Node.js project, and what is commonly included?
Ans: A .gitignore file specifies files and directories that should not be tracked by Git; in Node.js projects, this typically includes node_modules/, .env files, log files, and build output directories, keeping the repository clean and free of environment-specific or generated content.
NODE.JS #1.40
Q40: How do you read command-line arguments passed to a Node.js script?
Ans: Command-line arguments are available in the process.argv array, where the first two elements are the Node executable path and script path, with actual user-supplied arguments starting from index 2.
Code Example
// node script.js arg1 arg2
console.log(process.argv.slice(2)); // ['arg1', 'arg2']
NODE.JS #1.41
Q41: What is the difference between authentication and authorization in a Node.js API?
Ans: Authentication verifies who a user is (e.g., via login credentials or a token), while authorization determines what an authenticated user is permitted to do (e.g., access control based on roles or permissions).
NODE.JS #1.42
Q42: How do you set custom response headers in Express?
Ans: You use res.set(header, value) or res.setHeader(header, value) to add custom headers before sending the response.
Code Example
res.set('X-Custom-Header', 'value');
res.json({ ok: true });
NODE.JS #1.43
Q43: What is the difference between a 'dependency' and a 'devDependency' when installing with the --save-dev flag?
Ans: Using 'npm install --save-dev' (or -D) adds the package to devDependencies, indicating it's only needed for development/build/testing, whereas the default 'npm install ' adds it to dependencies, needed at runtime in production.
Medium 116 questions
NODE.JS #2.1
Q1: Is Node.js single-threaded or multi-threaded?
Ans: Node.js runs JavaScript code on a single main thread, but uses a libuv thread pool internally for certain operations (like file I/O and some crypto functions), and can leverage multiple processes/threads via clustering or worker_threads.
NODE.JS #2.2
Q2: What is the difference between npm and npx?
Ans: npm installs and manages packages, while npx executes a package's binary directly, optionally downloading it temporarily without a permanent install, useful for running one-off CLI tools.
Code Example
npx create-react-app my-app
NODE.JS #2.3
Q3: What is package-lock.json used for?
Ans: package-lock.json records the exact dependency tree and resolved versions installed, ensuring consistent installs across different machines and environments.
NODE.JS #2.4
Q4: What is semantic versioning (semver) and how does npm use it?
Ans: Semantic versioning uses a MAJOR.MINOR.PATCH format; npm uses prefixes like ^ (compatible with minor/patch updates) and ~ (compatible with patch updates only) in package.json to control how dependencies are updated.
NODE.JS #2.5
Q5: What is the difference between CommonJS and ES Modules in Node.js?
Ans: CommonJS uses require()/module.exports and loads modules synchronously, while ES Modules use import/export syntax, support static analysis and tree-shaking, and are loaded asynchronously; Node.js supports both, with ESM requiring a .mjs extension or type module in package.json.
Code Example
// CommonJS
module.exports = myFunction;
// ES Modules
export default myFunction;
NODE.JS #2.6
Q6: What is the difference between module.exports and exports?
Ans: Both initially reference the same object, but reassigning exports to a new object breaks its link to module.exports; only the object referenced by module.exports at the end is actually exported, so exports should only be used to add properties, not reassigned.
NODE.JS #2.7
Q7: What is the global object in Node.js?
Ans: In Node.js, the global object provides variables and functions available everywhere without needing to require them, such as process, console, setTimeout, and __dirname/__filename (module-scoped, not truly global).
NODE.JS #2.8
Q8: What is the process object in Node.js?
Ans: process is a global object providing information about and control over the current Node.js process, including process.argv (command-line arguments), process.env (environment variables), and process.exit().
Code Example
console.log(process.env.NODE_ENV);
console.log(process.argv);
NODE.JS #2.9
Q9: What is the difference between Node.js and Deno?
Ans: Deno is a newer JavaScript/TypeScript runtime created by Node.js's original author, offering built-in TypeScript support, secure-by-default permissions, and ES module imports via URLs, whereas Node.js uses npm and CommonJS/ESM with a more mature ecosystem.
NODE.JS #2.10
Q10: What is the event loop in Node.js?
Ans: The event loop is the core mechanism that allows Node.js to perform non-blocking I/O operations by offloading tasks to the system and executing callbacks once those tasks complete, despite JavaScript being single-threaded.
NODE.JS #2.11
Q11: What is callback hell and how can it be avoided?
Ans: Callback hell refers to deeply nested callbacks that make code hard to read and maintain, typically arising from chaining multiple asynchronous operations; it can be avoided using Promises, async/await, or named functions instead of nested anonymous callbacks.
NODE.JS #2.12
Q12: What is a Promise in JavaScript/Node.js?
Ans: A Promise represents the eventual result (or failure) of an asynchronous operation, existing in one of three states: pending, fulfilled, or rejected, and providing .then()/.catch()/.finally() for handling outcomes.
Code Example
fetch(url)
 .then(response => response.json())
 .then(data => console.log(data))
 .catch(err => console.error(err));
NODE.JS #2.13
Q13: What is async/await in Node.js?
Ans: async/await is syntactic sugar built on Promises, allowing asynchronous code to be written in a more synchronous-looking style; an async function always returns a Promise, and await pauses execution until a Promise resolves.
Code Example
async function getData() {
 try {
 const response = await fetch(url);
 const data = await response.json();
 return data;
 } catch (err) {
 console.error(err);
 }
}
NODE.JS #2.14
Q14: What is the difference between Promise.all() and Promise.allSettled()?
Ans: Promise.all() resolves when all promises fulfill, but rejects immediately if any single promise rejects; Promise.allSettled() waits for all promises to complete regardless of outcome, returning an array of each result's status (fulfilled or rejected).
Code Example
const results = await Promise.allSettled([p1, p2, p3]);
NODE.JS #2.15
Q15: How do you convert a callback-based function to a Promise-based one?
Ans: You can wrap the function in a new Promise, resolving or rejecting inside the callback, or use Node's built-in util.promisify() utility for standard error-first callback functions.
Code Example
const util = require('util');
const readFileAsync = util.promisify(fs.readFile);
const data = await readFileAsync('file.txt');
NODE.JS #2.16
Q16: Why is Node.js good for I/O-bound applications but less ideal for CPU-bound tasks?
Ans: Node.js's non-blocking, event-driven architecture excels at handling many concurrent I/O operations efficiently on a single thread, but CPU-intensive synchronous computations block the event loop, delaying all other pending operations until the computation finishes.
NODE.JS #2.17
Q17: What is the EventEmitter class in Node.js?
Ans: EventEmitter is a core Node.js class (from the events module) that implements the observer pattern, allowing objects to emit named events and register listener functions to respond to them.
Code Example
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', (name) => console.log(`Hello, ${name}`));
emitter.emit('greet', 'World');
NODE.JS #2.18
Q18: What is the difference between .on() and .once() on an EventEmitter?
Ans: .on() registers a listener that runs every time the event is emitted, while .once() registers a listener that runs only the first time the event is emitted and is then automatically removed.
NODE.JS #2.19
Q19: How do you remove an event listener in Node.js?
Ans: You can use emitter.removeListener(event, listener) or emitter.off(event, listener) to remove a specific listener, or removeAllListeners() to remove all listeners for an event.
Code Example
emitter.off('greet', myListener);
NODE.JS #2.20
Q20: Why is the event-driven architecture central to Node.js?
Ans: Node.js's core APIs (like streams, HTTP servers, and file operations) are built around EventEmitter and callbacks, allowing the runtime to efficiently notify application code when asynchronous operations complete without blocking the main thread.
NODE.JS #2.21
Q21: What is module caching in Node.js?
Ans: After a module is required once, Node.js caches the exported object; subsequent require() calls for the same file return the cached instance rather than re-executing the module's code.
NODE.JS #2.22
Q22: What is a scoped npm package?
Ans: A scoped package is namespaced under an organization or username using the @scope/package-name format, helping avoid naming collisions and grouping related packages, such as @angular/core.
NODE.JS #2.23
Q23: What is the fs.promises API?
Ans: fs.promises (or require('fs/promises')) provides Promise-based versions of the fs module's methods, allowing them to be used with async/await instead of callbacks.
Code Example
const fs = require('fs/promises');
const data = await fs.readFile('data.txt', 'utf8');
NODE.JS #2.24
Q24: What is a Stream in Node.js?
Ans: A Stream is an abstract interface for working with streaming data, processing it piece by piece (in chunks) rather than loading everything into memory at once, useful for large files or network data.
NODE.JS #2.25
Q25: What are the four types of streams in Node.js?
Ans: Node.js has Readable streams (data source, like fs.createReadStream), Writable streams (data destination), Duplex streams (both readable and writable, like a TCP socket), and Transform streams (a duplex stream that modifies data as it passes through, like zlib compression).
NODE.JS #2.26
Q26: What is the pipe() method used for in Node.js streams?
Ans: pipe() connects a readable stream's output directly to a writable stream's input, automatically managing data flow and backpressure without manual event handling.
Code Example
const fs = require('fs');
fs.createReadStream('input.txt').pipe(fs.createWriteStream('output.txt'));
NODE.JS #2.27
Q27: What is a Buffer in Node.js?
Ans: A Buffer is a Node.js class for handling raw binary data directly in memory, used when working with streams, files, or network protocols where data isn't naturally represented as UTF-8 text.
Code Example
const buf = Buffer.from('Hello', 'utf8');
console.log(buf); // <Buffer 48 65 6c 6c 6f>
NODE.JS #2.28
Q28: What is the difference between a Buffer and a String in Node.js?
Ans: A Buffer stores raw binary data as a fixed-length sequence of bytes, while a String represents text encoded in a specific character encoding (typically UTF-16 internally in JS); Buffers must be explicitly converted to strings using a specified encoding.
NODE.JS #2.29
Q29: How do you watch a file or directory for changes in Node.js?
Ans: The fs.watch() function monitors a file or directory for changes, invoking a callback with the event type (rename or change) and filename whenever a modification is detected.
Code Example
fs.watch('config.json', (eventType, filename) => {
 console.log(`${filename} changed: ${eventType}`);
});
NODE.JS #2.30
Q30: What is middleware in Express.js?
Ans: Middleware functions are functions that have access to the request, response, and the next middleware function in the application's request-response cycle, used for tasks like logging, authentication, and parsing request bodies.
Code Example
app.use((req, res, next) => {
 console.log(`${req.method} ${req.url}`);
 next();
});
NODE.JS #2.31
Q31: What is the purpose of the next() function in Express middleware?
Ans: next() passes control to the next middleware function in the stack; if not called (and the response isn't sent), the request will hang and never complete.
NODE.JS #2.32
Q32: How do you handle errors in Express.js?
Ans: Express uses special error-handling middleware functions with four parameters (err, req, res, next), placed after all other routes/middleware, to catch and respond to errors passed via next(err) or thrown in async handlers (with proper setup).
Code Example
app.use((err, req, res, next) => {
 console.error(err.stack);
 res.status(500).send('Something broke!');
});
NODE.JS #2.33
Q33: What is the difference between app.use() and app.get() in Express?
Ans: app.use() mounts middleware for all HTTP methods (and optionally a specific path prefix), while app.get() (and similar methods like post, put, delete) registers a handler specifically for that HTTP method and exact route.
NODE.JS #2.34
Q34: What is CORS and how do you enable it in an Express app?
Ans: CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to a different domain than the one that served them; it can be enabled in Express using the cors npm package or by manually setting appropriate response headers.
Code Example
const cors = require('cors');
app.use(cors());
NODE.JS #2.35
Q35: What is a REST API and how does Express help build one?
Ans: A REST API exposes resources via HTTP endpoints using standard methods (GET, POST, PUT, DELETE) mapped to CRUD operations; Express simplifies building REST APIs through its intuitive routing system and middleware ecosystem.
NODE.JS #2.36
Q36: How do you organize routes in a larger Express application?
Ans: You can use express.Router() to create modular, mountable route handlers grouped by resource or feature, keeping the main app file clean and organized.
Code Example
const router = express.Router();
router.get('/', (req, res) => res.send('User list'));
app.use('/users', router);
NODE.JS #2.37
Q37: How do you handle errors in asynchronous callback-based Node.js code?
Ans: Node.js conventionally uses the 'error-first callback' pattern, where the first argument to a callback is reserved for an error object (or null if no error occurred), which must be checked explicitly.
Code Example
fs.readFile('file.txt', (err, data) => {
 if (err) {
 console.error(err);
 return;
 }
 console.log(data);
});
NODE.JS #2.38
Q38: How do you handle errors in async/await functions?
Ans: You wrap the awaited code in a try-catch block, since a rejected awaited Promise throws an exception that can be caught synchronously within the async function.
Code Example
async function run() {
 try {
 const data = await fetchData();
 } catch (err) {
 console.error(err);
 }
}
NODE.JS #2.39
Q39: How do you create a custom error class in Node.js?
Ans: You create a class extending the built-in Error class, calling super(message) in the constructor and optionally adding custom properties like a status code.
Code Example
class NotFoundError extends Error {
 constructor(message) {
 super(message);
 this.name = 'NotFoundError';
 this.statusCode = 404;
 }
}
NODE.JS #2.40
Q40: What testing frameworks are commonly used with Node.js?
Ans: Popular Node.js testing frameworks include Jest, Mocha (often paired with Chai for assertions and Sinon for mocking), and the built-in node:test module introduced in recent Node.js versions.
NODE.JS #2.41
Q41: How do you write a basic unit test using Jest?
Ans: You use Jest's test() or it() function with a description and a callback containing assertions made with expect().
Code Example
test('adds 1 + 2 to equal 3', () => {
 expect(add(1, 2)).toBe(3);
});
NODE.JS #2.42
Q42: What is mocking in the context of Node.js testing?
Ans: Mocking replaces real dependencies (like database calls or external APIs) with fake implementations during tests, isolating the code under test and making tests faster and more predictable.
Code Example
jest.mock('./db');
db.getUser.mockResolvedValue({ id: 1, name: 'Tom' });
NODE.JS #2.43
Q43: How do you debug a Node.js application?
Ans: You can use the built-in inspector by running 'node --inspect app.js' and connecting Chrome DevTools, use console.log statements, or use an IDE's integrated debugger (like VS Code) with breakpoints.
Code Example
node --inspect-brk app.js
NODE.JS #2.44
Q44: What is the difference between console.log() and a proper logging library like Winston or Pino?
Ans: console.log() is simple but lacks log levels, structured output, and performance optimizations, while libraries like Winston or Pino provide configurable log levels, structured JSON output, and better performance for production logging needs.
NODE.JS #2.45
Q45: What is the child_process module used for?
Ans: child_process allows Node.js to spawn and interact with new OS-level processes, useful for running shell commands, executing other programs, or offloading CPU-intensive work.
Code Example
const { exec } = require('child_process');
exec('ls -la', (err, stdout) => console.log(stdout));
NODE.JS #2.46
Q46: What are common security best practices for Node.js applications?
Ans: Best practices include validating and sanitizing all user input, using parameterized queries to prevent SQL injection, keeping dependencies updated, setting secure HTTP headers (e.g., via helmet), rate-limiting requests, and never exposing detailed error stack traces to clients in production.
NODE.JS #2.47
Q47: What is the helmet package used for in Express applications?
Ans: helmet is a middleware collection that sets various HTTP security headers (like Content-Security-Policy and X-Frame-Options) to help protect Express apps from well-known web vulnerabilities.
Code Example
const helmet = require('helmet');
app.use(helmet());
NODE.JS #2.48
Q48: How do you prevent SQL injection in a Node.js application?
Ans: You should use parameterized queries or prepared statements provided by your database driver or ORM (like pg, mysql2, or Sequelize) instead of concatenating user input directly into SQL strings.
Code Example
const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
NODE.JS #2.49
Q49: How do you securely store passwords in a Node.js application?
Ans: Passwords should be hashed using a strong, slow hashing algorithm like bcrypt (via the bcrypt or bcryptjs package), never stored in plain text or reversibly encrypted.
Code Example
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 10);
const match = await bcrypt.compare(inputPassword, hash);
NODE.JS #2.50
Q50: What is JWT (JSON Web Token) and how is it used for authentication in Node.js?
Ans: JWT is a compact, signed token format used to securely transmit claims (like user identity) between parties; in Node.js, libraries like jsonwebtoken create and verify tokens, commonly used for stateless authentication in APIs.
Code Example
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 1 }, secretKey, { expiresIn: '1h' });
const decoded = jwt.verify(token, secretKey);
NODE.JS #2.51
Q51: What is rate limiting and how can you implement it in an Express app?
Ans: Rate limiting restricts how many requests a client can make within a given time window, protecting against abuse and denial-of-service attacks; it can be implemented with middleware like express-rate-limit.
Code Example
const rateLimit = require('express-rate-limit');
app.use(rateLimit({ windowMs: 15*60*1000, max: 100 }));
NODE.JS #2.52
Q52: Why should NODE_ENV be set to 'production' in a production deployment?
Ans: Setting NODE_ENV=production enables performance optimizations in frameworks like Express (such as view caching) and signals libraries to disable verbose debugging output, improving both speed and security.
NODE.JS #2.53
Q53: How do you connect to a MongoDB database in Node.js?
Ans: You can use the official MongoDB Node.js driver directly, or an ODM (Object Document Mapper) like Mongoose, which provides schema definitions and validation on top of MongoDB.
Code Example
const mongoose = require('mongoose');
await mongoose.connect('mongodb://localhost:27017/mydb');
NODE.JS #2.54
Q54: What is Mongoose and what problem does it solve?
Ans: Mongoose is an ODM library for MongoDB and Node.js that provides schema-based modeling for application data, including built-in type casting, validation, query building, and middleware hooks.
Code Example
const userSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model('User', userSchema);
NODE.JS #2.55
Q55: How do you connect to a PostgreSQL or MySQL database in Node.js?
Ans: You can use a database driver like pg (PostgreSQL) or mysql2 (MySQL) directly with connection pooling, or use an ORM like Sequelize, Prisma, or TypeORM for higher-level abstractions.
Code Example
const { Pool } = require('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const result = await pool.query('SELECT * FROM users');
NODE.JS #2.56
Q56: What is an ORM and what are some popular options for Node.js?
Ans: An ORM (Object-Relational Mapper) maps database tables to JavaScript objects/classes, abstracting raw SQL; popular Node.js options include Sequelize, TypeORM, and Prisma, each offering different styles of schema definition and query building.
NODE.JS #2.57
Q57: What is connection pooling and why is it important for database access in Node.js?
Ans: Connection pooling maintains a set of reusable database connections instead of opening and closing a new connection for every query, reducing overhead and improving performance under concurrent load.
NODE.JS #2.58
Q58: How do you handle database transactions in Node.js?
Ans: Most database drivers and ORMs provide transaction APIs (like a client.query('BEGIN')/COMMIT/ROLLBACK pattern with pg, or sequelize.transaction()) to group multiple operations so they either all succeed or all roll back together.
Code Example
await sequelize.transaction(async (t) => {
 await Account.update({ balance: newBalance }, { transaction: t });
});
NODE.JS #2.59
Q59: What is a closure in JavaScript?
Ans: A closure is a function that retains access to variables from its containing (outer) scope even after that outer function has finished executing.
Code Example
function counter() {
 let count = 0;
 return () => ++count;
}
const increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2
NODE.JS #2.60
Q60: What is the 'this' keyword in JavaScript and how does it behave differently in arrow functions?
Ans: 'this' refers to the context in which a function is called, which can vary based on how the function is invoked; arrow functions do not have their own 'this' and instead lexically inherit it from the enclosing scope, unlike regular functions.
Code Example
const obj = {
 name: 'Tom',
 regular: function() { console.log(this.name); }, // 'Tom'
 arrow: () => { console.log(this.name); } // undefined, inherits outer scope
};
NODE.JS #2.61
Q61: What is prototypal inheritance in JavaScript?
Ans: JavaScript objects inherit properties and methods from a prototype object; when a property isn't found on an object, the JavaScript engine looks up the prototype chain until it finds the property or reaches null.
NODE.JS #2.62
Q62: What is the difference between a JavaScript class and a constructor function?
Ans: ES6 classes are primarily syntactic sugar over JavaScript's existing prototype-based inheritance, providing a cleaner syntax for defining constructor functions and methods, though classes also enforce being called with 'new' and have stricter semantics.
Code Example
class Animal {
 constructor(name) { this.name = name; }
 speak() { console.log(`${this.name} makes a sound`); }
}
NODE.JS #2.63
Q63: What is destructuring assignment in JavaScript?
Ans: Destructuring allows extracting values from arrays or properties from objects into distinct variables using a concise syntax.
Code Example
const { name, age } = person;
const [first, second] = [1, 2];
NODE.JS #2.64
Q64: What is the spread operator used for in JavaScript?
Ans: The spread operator (...) expands an iterable (array, string) or object's own enumerable properties into individual elements, useful for copying, merging, or passing arguments.
Code Example
const arr2 = [...arr1, 4, 5];
const merged = { ...obj1, ...obj2 };
NODE.JS #2.65
Q65: What are JavaScript Promises' three states?
Ans: A Promise can be pending (initial state, neither fulfilled nor rejected), fulfilled (operation completed successfully), or rejected (operation failed), and once settled (fulfilled or rejected), its state cannot change again.
NODE.JS #2.66
Q66: What is hoisting in JavaScript?
Ans: Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their containing scope during compilation; var declarations are hoisted and initialized as undefined, function declarations are fully hoisted, while let/const are hoisted but remain uninitialized until their declaration line.
NODE.JS #2.67
Q67: What is an IIFE (Immediately Invoked Function Expression)?
Ans: An IIFE is a function that is defined and executed immediately after its creation, often used to create a private scope and avoid polluting the global namespace.
Code Example
(function() {
 console.log('Runs immediately');
})();
NODE.JS #2.68
Q68: How can you improve the performance of a Node.js application?
Ans: Common strategies include using asynchronous non-blocking APIs, caching frequent results (e.g., with Redis), enabling gzip compression, using clustering to utilize multiple CPU cores, optimizing database queries, and profiling to find bottlenecks.
NODE.JS #2.69
Q69: What is PM2 and why is it used with Node.js applications?
Ans: PM2 is a production process manager for Node.js applications that provides features like automatic restarts on crashes, load balancing across CPU cores (cluster mode), log management, and zero-downtime reloads.
Code Example
pm2 start app.js -i max
pm2 list
pm2 logs
NODE.JS #2.70
Q70: What is horizontal scaling versus vertical scaling for a Node.js application?
Ans: Vertical scaling increases the resources (CPU, memory) of a single server instance, while horizontal scaling adds more instances of the application running behind a load balancer, which Node.js's stateless, clusterable nature is well suited for.
NODE.JS #2.71
Q71: What is a reverse proxy and why is it commonly used in front of Node.js applications?
Ans: A reverse proxy (like Nginx) sits in front of the Node.js application, handling tasks like SSL termination, load balancing, static file serving, and request buffering, offloading work that Node.js doesn't need to handle directly.
NODE.JS #2.72
Q72: What is the purpose of compression middleware in an Express app?
Ans: Compression middleware (like the compression npm package) gzips HTTP responses before sending them to the client, reducing payload size and improving load times over the network.
Code Example
const compression = require('compression');
app.use(compression());
NODE.JS #2.73
Q73: What is caching and how might you implement it in a Node.js API?
Ans: Caching stores the results of expensive or frequently repeated operations (like database queries) so subsequent requests can be served faster; it can be implemented in-memory, or using an external store like Redis for shared caching across multiple server instances.
Code Example
const cached = await redisClient.get(key);
if (cached) return JSON.parse(cached);
NODE.JS #2.74
Q74: What environment-specific configuration strategies are common in Node.js apps?
Ans: Common strategies include using environment variables (via process.env and dotenv), separate config files per environment, or configuration management libraries, allowing behavior (like database URLs or log levels) to differ between development, staging, and production.
NODE.JS #2.75
Q75: What are WebSockets and how do they differ from HTTP requests?
Ans: WebSockets provide a persistent, full-duplex communication channel between client and server over a single TCP connection, allowing real-time bidirectional data exchange, unlike HTTP's request-response model which requires a new request for each exchange.
NODE.JS #2.76
Q76: What is Socket.IO and how does it relate to WebSockets?
Ans: Socket.IO is a library that enables real-time, bidirectional communication, built on top of WebSockets with automatic fallback to other transport methods (like long polling) for compatibility, plus features like rooms and automatic reconnection.
Code Example
const io = require('socket.io')(server);
io.on('connection', (socket) => {
 socket.on('message', (msg) => io.emit('message', msg));
});
NODE.JS #2.77
Q77: What is GraphQL and how does it differ from a REST API?
Ans: GraphQL is a query language for APIs that allows clients to request exactly the data they need in a single request, unlike REST which typically exposes fixed endpoints returning predetermined data structures, often requiring multiple requests for related resources.
NODE.JS #2.78
Q78: What is Apollo Server and how is it used with Node.js?
Ans: Apollo Server is a popular, production-ready GraphQL server library for Node.js that integrates with frameworks like Express, allowing you to define a GraphQL schema and resolvers to handle queries and mutations.
NODE.JS #2.79
Q79: What is API versioning and how might you implement it in an Express app?
Ans: API versioning allows an API to evolve without breaking existing clients, commonly implemented via URL path prefixes (like /api/v1/), custom headers, or query parameters to indicate which version of the API a client wants to use.
Code Example
app.use('/api/v1', v1Router);
app.use('/api/v2', v2Router);
NODE.JS #2.80
Q80: What is the crypto module used for in Node.js?
Ans: The crypto module provides cryptographic functionality including hashing, HMAC, encryption/decryption, and generating secure random values, built on OpenSSL.
Code Example
const crypto = require('crypto');
const hash = crypto.createHash('sha256').update('data').digest('hex');
NODE.JS #2.81
Q81: How do you generate a secure random string or token in Node.js?
Ans: crypto.randomBytes() generates cryptographically strong pseudo-random data, which can be converted to a hex or base64 string, suitable for tokens, session IDs, or salts.
Code Example
const token = crypto.randomBytes(32).toString('hex');
NODE.JS #2.82
Q82: What is the util module used for in Node.js?
Ans: The util module provides utility functions for debugging and working with Node.js internals, such as util.promisify() (converting callback functions to Promises) and util.inspect() (for detailed object string representations).
NODE.JS #2.83
Q83: What is the zlib module used for in Node.js?
Ans: The zlib module provides compression and decompression functionality (gzip, deflate, brotli) implemented as Transform streams, useful for compressing HTTP responses or files.
Code Example
const zlib = require('zlib');
fs.createReadStream('file.txt').pipe(zlib.createGzip()).pipe(fs.createWriteStream('file.txt.gz'));
NODE.JS #2.84
Q84: What is the querystring module used for, and how does it differ from the URL API?
Ans: The legacy querystring module parses and formats URL query strings, while the more modern URL and URLSearchParams APIs (globally available in Node.js) provide a standards-based, more robust way to parse full URLs and their query parameters.
Code Example
const { URL } = require('url');
const myUrl = new URL('https://example.com/page?name=Tom');
console.log(myUrl.searchParams.get('name'));
NODE.JS #2.85
Q85: What is the assert module used for in Node.js?
Ans: The built-in assert module provides functions for writing simple runtime assertions, primarily used for internal testing, throwing an AssertionError if a given condition fails.
Code Example
const assert = require('assert');
assert.strictEqual(1 + 1, 2);
NODE.JS #2.86
Q86: What is the difference between process.exit() and allowing a Node.js process to end naturally?
Ans: process.exit() immediately terminates the process, potentially cutting off pending asynchronous operations (like unflushed writes), while letting the process end naturally allows the event loop to drain all pending callbacks and I/O before exiting.
NODE.JS #2.87
Q87: What are process signals and how can a Node.js application handle them?
Ans: Signals like SIGINT (Ctrl+C) and SIGTERM (graceful shutdown request) can be intercepted using process.on('SIGTERM', handler), allowing an application to perform cleanup (like closing database connections) before exiting.
Code Example
process.on('SIGTERM', async () => {
 await closeConnections();
 process.exit(0);
});
NODE.JS #2.88
Q88: What is a monorepo and how is it typically managed in the Node.js ecosystem?
Ans: A monorepo stores multiple related packages or projects within a single repository; tools like npm/yarn/pnpm workspaces, Lerna, or Nx help manage dependencies and versioning across the packages within a monorepo.
NODE.JS #2.89
Q89: How do you use TypeScript with Node.js?
Ans: You install TypeScript and type definitions (like @types/node) as dev dependencies, write .ts files, and compile them to JavaScript using the tsc compiler (or run directly with tools like ts-node) before or during execution.
Code Example
npm install -D typescript @types/node
npx tsc --init
NODE.JS #2.90
Q90: What is the difference between a microservice architecture and a monolithic architecture for Node.js applications?
Ans: A monolithic architecture builds the entire application as a single deployable unit, while a microservice architecture splits functionality into smaller, independently deployable services (often communicating via HTTP or message queues), improving scalability and team autonomy at the cost of added operational complexity.
NODE.JS #2.91
Q91: What is a message queue and why might you use one with Node.js?
Ans: A message queue (like RabbitMQ or Kafka) enables asynchronous communication between services by decoupling producers and consumers of messages, improving reliability and scalability, especially useful for background job processing or event-driven microservices.
NODE.JS #2.92
Q92: What is graceful shutdown in a Node.js server and why is it important?
Ans: Graceful shutdown involves stopping the server from accepting new connections, allowing in-flight requests to complete, and cleanly closing resources (like database connections) before the process exits, preventing dropped requests or data corruption during deployments or restarts.
Code Example
server.close(() => {
 console.log('Server closed gracefully');
 process.exit(0);
});
NODE.JS #2.93
Q93: How do you handle file uploads in an Express application?
Ans: Middleware like multer handles multipart/form-data requests, parsing uploaded files and making them available via req.file or req.files, while storing them to disk, memory, or a cloud storage service.
Code Example
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('photo'), (req, res) => {
 res.send(req.file);
});
NODE.JS #2.94
Q94: What is idempotency in the context of REST APIs, and which HTTP methods are idempotent?
Ans: An idempotent operation produces the same result no matter how many times it's performed; GET, PUT, and DELETE are generally idempotent, while POST is typically not, since repeating it often creates additional resources.
NODE.JS #2.95
Q95: What is the difference between PUT and PATCH HTTP methods?
Ans: PUT typically replaces an entire resource with the provided representation, while PATCH applies a partial update, modifying only the specified fields of an existing resource.
NODE.JS #2.96
Q96: What is a health check endpoint and why is it useful in a Node.js service?
Ans: A health check endpoint (like GET /health) returns the service's operational status, used by load balancers, orchestrators (like Kubernetes), or monitoring tools to determine whether an instance is ready to receive traffic or needs to be restarted.
Code Example
app.get('/health', (req, res) => res.status(200).json({ status: 'ok' }));
NODE.JS #2.97
Q97: How do you validate incoming request data in an Express API?
Ans: You can use validation libraries like Joi, express-validator, or Zod to define schemas and validate/sanitize req.body, req.query, or req.params before processing the request.
Code Example
const { body, validationResult } = require('express-validator');
app.post('/users', body('email').isEmail(), (req, res) => {
 const errors = validationResult(req);
 if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
});
NODE.JS #2.98
Q98: What is the difference between session-based authentication and token-based (JWT) authentication in Node.js apps?
Ans: Session-based authentication stores session state on the server (often referenced via a cookie), requiring server-side storage and lookup, while token-based authentication (like JWT) is stateless, embedding user claims directly in a signed token that the server can verify without a database lookup.
NODE.JS #2.99
Q99: What is the difference between npm install and npm ci?
Ans: npm install installs dependencies based on package.json and may update package-lock.json, while npm ci performs a clean, reproducible install strictly following package-lock.json, deleting node_modules first, making it faster and more reliable for CI/CD environments.
NODE.JS #2.100
Q100: How do you publish a package to the npm registry?
Ans: After creating an npm account and logging in via 'npm login', you run 'npm publish' from the package's root directory (with a properly configured package.json), optionally bumping the version first with 'npm version'.
Code Example
npm login
npm version patch
npm publish
NODE.JS #2.101
Q101: What is the difference between an Express route handler and a middleware function in terms of signature?
Ans: Both share a similar (req, res, next) signature, but a route handler typically ends the request-response cycle by sending a response, while middleware often performs a task and calls next() to pass control onward, though the distinction is more about usage than syntax.
NODE.JS #2.102
Q102: What is the purpose of Content-Type and Accept headers in HTTP requests?
Ans: Content-Type indicates the media type of the data being sent in the request/response body (like application/json), while Accept indicates what media types the client is willing to receive in the response, allowing content negotiation.
NODE.JS #2.103
Q103: What is Docker and why is it commonly used to deploy Node.js applications?
Ans: Docker packages an application and its dependencies into a portable container image, ensuring consistent behavior across development, testing, and production environments; Node.js apps are commonly containerized using a Dockerfile that installs dependencies and defines a start command.
Code Example
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
CMD ["node", "index.js"]
NODE.JS #2.104
Q104: What is serverless computing and how does it relate to Node.js?
Ans: Serverless computing (like AWS Lambda) lets you run code (often Node.js functions) without managing servers, automatically scaling and charging based on execution time, well-suited for Node.js due to its fast cold-start times relative to some other runtimes.
NODE.JS #2.105
Q105: What is the difference between supertest and a typical HTTP client library for testing Express apps?
Ans: supertest is specifically designed for testing HTTP servers (like Express apps) by wrapping the app instance directly, allowing assertions on responses without needing to actually bind to a network port, making tests faster and more self-contained.
Code Example
const request = require('supertest');
const response = await request(app).get('/users').expect(200);
NODE.JS #2.106
Q106: What is the difference between Buffer.from() and Buffer.alloc()?
Ans: Buffer.from() creates a buffer initialized with existing data (like a string or array), while Buffer.alloc() creates a new buffer of a specified size, initialized to zero by default for safety (unlike the deprecated, unsafe new Buffer(size)).
Code Example
const buf1 = Buffer.from('hello');
const buf2 = Buffer.alloc(10);
NODE.JS #2.107
Q107: What is the difference between http and https modules in Node.js?
Ans: The http module creates plain, unencrypted HTTP servers/clients, while the https module creates TLS/SSL-encrypted servers/clients, requiring a certificate and private key for the server.
Code Example
const https = require('https');
const options = { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') };
https.createServer(options, handler).listen(443);
NODE.JS #2.108
Q108: What is CSRF and how might you protect an Express application against it?
Ans: CSRF (Cross-Site Request Forgery) tricks a logged-in user's browser into making unwanted requests to your app; protection typically involves using anti-CSRF tokens embedded in forms (e.g., via the csurf middleware, though it's now deprecated in favor of alternatives) and setting proper SameSite cookie attributes.
NODE.JS #2.109
Q109: What is middleware chaining and how does error propagate through it in Express?
Ans: Multiple middleware functions can be chained in sequence for a route; calling next() passes control to the next one, while calling next(err) skips remaining regular middleware and jumps directly to the nearest error-handling middleware.
NODE.JS #2.110
Q110: What does the engines field in package.json specify?
Ans: The engines field declares which versions of Node.js (and optionally npm) a package is compatible with, which can be enforced during installation or used informationally by tooling and hosting platforms.
Code Example
"engines": { "node": ">=18.0.0" }
NODE.JS #2.111
Q111: What is the difference between Object.freeze() and const for immutability in JavaScript?
Ans: const only prevents reassignment of the variable binding itself, not mutation of the object it references, while Object.freeze() prevents adding, removing, or modifying an object's own properties (shallowly), making the object itself immutable.
Code Example
const obj = Object.freeze({ a: 1 });
obj.a = 2; // silently fails (or throws in strict mode)
console.log(obj.a); // 1
NODE.JS #2.112
Q112: What is the difference between the Node.js http.Server 'request' event and using Express route handlers?
Ans: The raw http module emits a single 'request' event for every incoming request, requiring manual URL/method parsing and routing logic, while Express builds on top of this, providing a declarative routing API, middleware pipeline, and many convenience methods out of the box.
NODE.JS #2.113
Q113: What is the purpose of the .npmrc file?
Ans: .npmrc is a configuration file for npm that can set options like the registry URL, authentication tokens, or default settings, applicable at the project, user, or global level.
NODE.JS #2.114
Q114: What is the difference between res.send(), res.json(), and res.end() in Express?
Ans: res.json() explicitly serializes the argument to JSON and sets the Content-Type header accordingly, res.send() is more flexible and infers the content type based on the argument's type (string, object, buffer), and res.end() simply ends the response, optionally with raw data, without content-type inference.
NODE.JS #2.115
Q115: What is the purpose of a lockfile like package-lock.json or yarn.lock beyond version pinning?
Ans: Besides pinning exact resolved versions, lockfiles record the integrity hashes of installed packages, ensuring the exact same code is installed every time, protecting against supply-chain tampering or unexpected changes in a dependency's published content.
NODE.JS #2.116
Q116: What is the difference between yarn, npm, and pnpm as package managers?
Ans: All three manage Node.js dependencies, but differ in implementation: npm is the default bundled manager, yarn historically offered faster, more deterministic installs (features since adopted by npm), and pnpm uses a content-addressable storage system with symlinks to save disk space by avoiding duplicate package copies across projects.
Hard 38 questions
NODE.JS #3.1
Q1: What are the phases of the Node.js event loop?
Ans: The main phases are: timers (setTimeout/setInterval callbacks), pending callbacks, poll (retrieving new I/O events), check (setImmediate callbacks), and close callbacks, cycling repeatedly while the process runs.
NODE.JS #3.2
Q2: What is the difference between process.nextTick() and setImmediate()?
Ans: process.nextTick() queues a callback to run immediately after the current operation completes, before the event loop continues to the next phase, while setImmediate() queues a callback to run in the check phase of the next event loop iteration.
Code Example
process.nextTick(() => console.log('nextTick'));
setImmediate(() => console.log('immediate'));
console.log('sync');
NODE.JS #3.3
Q3: What is the difference between Promise.race() and Promise.any()?
Ans: Promise.race() resolves or rejects as soon as the first promise settles (whether fulfilled or rejected), while Promise.any() resolves as soon as the first promise fulfills, only rejecting if all promises reject.
NODE.JS #3.4
Q4: How can you handle CPU-intensive tasks in Node.js without blocking the event loop?
Ans: You can offload CPU-intensive work to worker threads (via the worker_threads module), child processes, or a separate microservice, keeping the main event loop free to handle I/O.
Code Example
const { Worker } = require('worker_threads');
const worker = new Worker('./heavy-task.js');
NODE.JS #3.5
Q5: What is the microtask queue and how does it relate to the event loop?
Ans: The microtask queue holds callbacks from resolved Promises (and process.nextTick callbacks in Node), which are processed completely after the current synchronous code finishes but before the event loop proceeds to the next macrotask (like a timer callback).
NODE.JS #3.6
Q6: What happens if an EventEmitter emits an 'error' event with no listener attached?
Ans: If there is no listener for the 'error' event, Node.js throws the error and crashes the process, so it's considered best practice to always attach an error listener to EventEmitters that may emit errors.
NODE.JS #3.7
Q7: What is the module wrapper function in Node.js?
Ans: Node.js wraps every CommonJS module's code in a function providing the exports, require, module, __filename, and __dirname parameters, giving each module its own private scope.
Code Example
(function(exports, require, module, __filename, __dirname) {
 // module code
});
NODE.JS #3.8
Q8: How does Node.js resolve a require('./module') call?
Ans: Node.js looks for an exact file match first, then tries appending extensions like .js, .json, and .node, and if it's a directory, looks for an index.js file or a 'main' field in that directory's package.json.
NODE.JS #3.9
Q9: What is backpressure in the context of Node.js streams?
Ans: Backpressure occurs when a writable stream cannot process incoming data as fast as a readable stream produces it; Node.js streams handle this automatically when using pipe(), pausing the readable stream until the writable stream catches up.
NODE.JS #3.10
Q10: What is an uncaught exception in Node.js and how can you handle it globally?
Ans: An uncaught exception is a synchronous error not caught by any try-catch block, which by default crashes the process; you can listen for process.on('uncaughtException', handler) as a last-resort safety net, though it's best practice to let the process exit and restart via a process manager after logging.
Code Example
process.on('uncaughtException', (err) => {
 console.error('Uncaught exception:', err);
 process.exit(1);
});
NODE.JS #3.11
Q11: What is an unhandled promise rejection and how do you catch it globally?
Ans: An unhandled rejection occurs when a Promise rejects without a .catch() handler; you can listen for process.on('unhandledRejection', handler) to log or handle such cases globally, though Node.js may terminate the process by default in newer versions.
Code Example
process.on('unhandledRejection', (reason, promise) => {
 console.error('Unhandled Rejection:', reason);
});
NODE.JS #3.12
Q12: What is the difference between operational errors and programmer errors in Node.js?
Ans: Operational errors are runtime problems in a correctly written program (like a failed network request or invalid user input) that should be handled gracefully, while programmer errors are bugs (like accessing a property of undefined) that generally indicate the process should be restarted rather than recovered from.
NODE.JS #3.13
Q13: What is the difference between exec(), execFile(), spawn(), and fork() in child_process?
Ans: exec() runs a command in a shell and buffers the entire output; execFile() runs an executable directly without a shell; spawn() launches a process and streams output incrementally, better for large data; fork() specifically spawns a new Node.js process with a built-in IPC channel for message passing.
NODE.JS #3.14
Q14: What is the cluster module used for in Node.js?
Ans: The cluster module allows a Node.js application to spawn multiple worker processes (typically one per CPU core) that share the same server port, improving throughput and resilience by utilizing multiple cores despite Node.js's single-threaded nature.
Code Example
const cluster = require('cluster');
const os = require('os');
if (cluster.isPrimary) {
 for (let i = 0; i < os.cpus().length; i++) cluster.fork();
} else {
 require('./server');
}
NODE.JS #3.15
Q15: What is the difference between cluster and worker_threads in Node.js?
Ans: cluster creates multiple independent processes (each with its own memory and event loop) primarily to scale network servers across CPU cores, while worker_threads creates threads within the same process that can share memory (via SharedArrayBuffer), better suited for CPU-intensive computations.
NODE.JS #3.16
Q16: How do parent and child processes communicate in Node.js when using fork()?
Ans: fork() automatically sets up an IPC (inter-process communication) channel, allowing the parent and child to send messages to each other using process.send() and listening with the 'message' event.
Code Example
// parent.js
const child = require('child_process').fork('child.js');
child.send({ hello: 'world' });
child.on('message', msg => console.log(msg));
NODE.JS #3.17
Q17: What are JavaScript Symbols used for?
Ans: A Symbol is a unique and immutable primitive value often used as a special, collision-free property key on objects, useful for defining semi-private object properties or well-known meta-behaviors (like Symbol.iterator).
NODE.JS #3.18
Q18: What is memory leak detection in Node.js and what tools can help?
Ans: A memory leak occurs when an application unintentionally retains references to objects, preventing garbage collection and causing memory usage to grow over time; tools like the built-in --inspect flag with Chrome DevTools, heap snapshots, and clinic.js can help identify leaks.
NODE.JS #3.19
Q19: What is HATEOAS in the context of REST APIs?
Ans: HATEOAS (Hypermedia as the Engine of Application State) is a REST constraint where API responses include links to related actions or resources, allowing clients to navigate the API dynamically rather than hardcoding endpoint URLs.
NODE.JS #3.20
Q20: What is the difference between synchronous middleware and asynchronous middleware in Express?
Ans: Synchronous middleware executes and calls next() immediately, while asynchronous middleware (using Promises or async/await) must properly handle errors (e.g., wrapping with a try-catch and calling next(err), or using a wrapper utility) since unhandled async errors won't be automatically caught by Express's default error handling.
NODE.JS #3.21
Q21: What is the difference between a Node.js Buffer and a TypedArray?
Ans: Buffer is a Node.js-specific subclass of Uint8Array (a TypedArray) with additional Node-specific convenience methods for encoding/decoding, and both provide a fixed-length view over raw binary data.
NODE.JS #3.22
Q22: What is the difference between an ESM default export and a named export when required from CommonJS?
Ans: When a CommonJS module requires an ES Module, the ESM's default export is accessed via the .default property of the imported object, while named exports are accessed as properties directly, since Node.js wraps the ESM's exports in an interop object.
NODE.JS #3.23
Q23: What is the difference between synchronous logging and asynchronous logging performance implications in Node.js?
Ans: Synchronous logging (like writing directly and waiting) can block the event loop under heavy load, while asynchronous, buffered logging libraries (like Pino) minimize performance impact by writing logs without blocking the main thread's request processing.
NODE.JS #3.24
Q24: What is the difference between a synchronous stack overflow and an event loop blocking issue in Node.js?
Ans: A stack overflow occurs from excessive nested/recursive synchronous function calls exceeding the call stack size, crashing with a RangeError, while event loop blocking occurs when a long-running synchronous operation (like a heavy loop) prevents the event loop from processing other pending callbacks, without necessarily crashing.
NODE.JS #3.25
Q25: What is the difference between npm workspaces and a tool like Lerna for monorepos?
Ans: npm workspaces (built into npm 7+) provide native support for managing multiple packages within a single repository, handling shared dependency hoisting and cross-package linking, while Lerna is a third-party tool that adds additional monorepo-specific features like versioning and publishing workflows, and can be used alongside or instead of workspaces.
NODE.JS #3.26
Q26: What is the difference between readable stream 'flowing' and 'paused' modes?
Ans: In flowing mode, data is read from the underlying system automatically and emitted via 'data' events as fast as possible, while in paused mode, you must explicitly call stream.read() to retrieve chunks of data, giving more manual control over consumption.
NODE.JS #3.27
Q27: How do you create a custom readable stream in Node.js?
Ans: You extend the stream.Readable class and implement the _read() method, pushing data using this.push() and signaling the end of the stream by pushing null.
Code Example
const { Readable } = require('stream');
class MyStream extends Readable {
 _read() {
 this.push('data chunk');
 this.push(null); // end stream
 }
}
NODE.JS #3.28
Q28: What is the SameSite cookie attribute and why does it matter for security?
Ans: SameSite controls whether a cookie is sent with cross-site requests; setting it to 'Strict' or 'Lax' helps mitigate CSRF attacks by preventing the browser from automatically including the cookie on requests originating from other sites.
NODE.JS #3.29
Q29: What is the difference between a synchronous route handler throwing an error and an async route handler throwing an error in Express (pre-Express 5)?
Ans: In versions before Express 5, a thrown error in a synchronous handler is automatically caught by Express's default mechanism, but an error thrown inside an async function (rejected Promise) is not automatically caught and must be explicitly passed to next(err) or handled with a wrapper utility, otherwise it becomes an unhandled rejection.
NODE.JS #3.30
Q30: What is a common pattern for wrapping async Express route handlers to catch errors automatically?
Ans: A helper function wraps the async handler in a try-catch (or uses .catch(next) on the returned Promise), forwarding any error to next() so Express's error-handling middleware can process it consistently.
Code Example
const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
app.get('/users', asyncHandler(async (req, res) => {
 const users = await getUsers();
 res.json(users);
}));
NODE.JS #3.31
Q31: What is the difference between a hard dependency and a peer dependency in package.json?
Ans: A regular dependency is installed automatically alongside the package that requires it, while a peerDependency signals that the package expects the consuming project to provide a compatible version itself (commonly used by plugins that must share the exact instance of a host library, like React or Express).
NODE.JS #3.32
Q32: What is clustering's main limitation regarding shared in-memory state?
Ans: Since each cluster worker is a separate process with its own memory space, in-memory data (like a cache or session store) is not automatically shared between workers, requiring an external shared store (like Redis) for consistent state across the cluster.
NODE.JS #3.33
Q33: What is the difference between synchronous crypto hashing and bcrypt's intentional slowness?
Ans: General-purpose hash functions (like SHA-256) are designed to be extremely fast, making them unsuitable for password hashing since attackers can brute-force them quickly, while bcrypt is intentionally slow and configurable (via a cost factor) specifically to resist brute-force password cracking.
NODE.JS #3.34
Q34: What is the difference between require.cache and clearing a module's cached export?
Ans: require.cache is an object where Node.js stores already-loaded modules keyed by their resolved file path; deleting an entry from require.cache forces the next require() call for that path to re-execute and re-cache the module, useful in certain hot-reloading or testing scenarios.
Code Example
delete require.cache[require.resolve('./myModule')];
NODE.JS #3.35
Q35: What is the difference between a Node.js Timer object returned by setTimeout and the underlying OS timer?
Ans: The object returned by setTimeout() is a Node.js Timeout object providing methods like .unref() (allowing the process to exit even if the timer is still pending) and .ref(), managed internally by libuv's timer implementation rather than directly by the OS.
NODE.JS #3.36
Q36: What is the purpose of the Content-Length and Transfer-Encoding: chunked headers in HTTP responses?
Ans: Content-Length specifies the exact size of the response body in bytes, while Transfer-Encoding: chunked is used when the total size isn't known upfront, allowing the response to be sent in a series of chunks, common with streaming responses.
NODE.JS #3.37
Q37: What is a Node.js worker_threads module used for?
Ans: worker_threads allows running JavaScript in parallel on separate threads within the same process, useful for CPU-intensive tasks, and supports sharing memory between threads via SharedArrayBuffer, unlike child processes which have fully isolated memory.
NODE.JS #3.38
Q38: What is the difference between synchronous compression and streaming compression using zlib?
Ans: Synchronous methods like zlib.gzipSync() compress an entire buffer in memory at once and block execution, while streaming compression (piping through zlib.createGzip()) processes data incrementally in chunks, using less memory for large files and not blocking the event loop.