120+ Node.js Interview Questions & Answers
Basics & Fundamentals (1-15)
-
1. What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers to use JavaScript to write server-side applications, enabling full-stack JavaScript development.
-
2. What are the key features of Node.js?
- - Event-driven, non-blocking I/O model
- - Built on V8 engine for fast execution
- - NPM (Node Package Manager) for package management
- - Single-threaded with asynchronous capabilities
- - Suitable for data-intensive, real-time applications
- - Cross-platform compatibility
-
3. What is the event-driven architecture in Node.js?
Node.js uses an event-driven architecture where operations emit events that can be listened to. The EventEmitter class is central to this, allowing objects to emit named events and register listeners for those events.
-
4. Explain the Node.js event loop.
The event loop is a mechanism that continuously checks for tasks in the call stack and callback queue. It processes synchronous code first, then handles asynchronous callbacks in phases (timers, pending callbacks, idle/prepare, poll, check, close callbacks).
-
5. What is the difference between Node.js and JavaScript?
JavaScript is a programming language that runs in browsers and Node.js. Node.js extends JavaScript with server-side capabilities, file system access, networking, and system operations. Node.js doesn't have browser APIs like DOM or Window object.
-
6. What is the global object in Node.js?
The global object in Node.js is similar to
windowin browsers. It contains global functions and variables likeconsole,process,Buffer, andsetTimeout. You can access it using theglobalkeyword. -
7. Explain the Node.js architecture.
Node.js architecture consists of:
- - V8 Engine: Compiles JavaScript to machine code
- - libuv: Provides event loop and async I/O
- - Node.js Bindings: Connect JavaScript to C++ libraries
- - Core Libraries: Built-in modules
-
8. What is REPL in Node.js?
REPL (Read-Eval-Print Loop) is an interactive shell where you can execute JavaScript code. Start it by typing
nodein the terminal. It's useful for testing code snippets and exploring Node.js APIs. -
9. What is the difference between global and module.exports?
globalis the global namespace accessible everywhere in Node.js.module.exportsis used to export functionality from a specific module. Variables declared in a module are local to that module unless explicitly exported. -
10. What is the Node.js callback?
A callback is a function passed as an argument to another function, to be executed after a certain operation has been completed. Node.js heavily uses callbacks for asynchronous operations.
function greeting(name, callback) { console.log('Hello ' + name); callback(); } greeting('John', function() { console.log('Callback called'); }); -
11. What is the purpose of package.json?
package.jsonis a metadata file that describes the project and its dependencies. It contains project name, version, description, entry point, scripts, and dependency lists. It's essential for any Node.js project. -
12. What is npm (Node Package Manager)?
npm is the default package manager for Node.js. It allows you to install, manage, and share reusable code packages. npm consists of three components: website, CLI, and registry.
-
13. How do you create a Node.js application?
- - Create a project directory
-
- Initialize with
npm initto create package.json -
- Install dependencies with
npm install - - Create your JavaScript files
-
- Run with
node filename.jsor using npm scripts
-
14. What is the difference between
require()andimport?require()is CommonJS syntax used traditionally in Node.js, whileimportis ES6 module syntax. Node.js now supports both, butrequire()is still the default.importoffers better tree-shaking and static analysis. -
15. What is the process object in Node.js?
The
processobject provides information about the current Node.js process. It includes properties likeprocess.version,process.platform,process.argv, and methods likeprocess.exit(),process.env, andprocess.cwd().
Core Concepts (16-30)
-
16. What is the difference between synchronous and asynchronous operations?
Synchronous operations block execution until complete, while asynchronous operations don't. In Node.js, asynchronous operations are preferred for I/O to prevent blocking the event loop.
-
17. What is callback hell (pyramid of doom)?
Callback hell occurs when multiple nested callbacks make code hard to read and maintain:
getData(function(a){ getMoreData(a, function(b){ getMoreData(b, function(c){ getMoreData(c, function(d){ // nested callbacks }); }); }); }); -
18. What are Promises in Node.js?
Promises are objects representing the eventual completion (or failure) of an asynchronous operation. They have three states: pending, fulfilled, and rejected. Promises provide better error handling than callbacks.
const promise = new Promise((resolve, reject) => { if (Math.random() > 0.5) resolve('Success'); else reject('Error'); }); -
19. What are async/await functions?
Async/await is syntactic sugar over Promises, making asynchronous code look synchronous. An async function returns a Promise, and await pauses execution until the Promise settles.
async function fetchData() { try { const data = await getData(); console.log(data); } catch(error) { console.log(error); } } -
20. What is the purpose of the
thiskeyword in Node.js?In Node.js,
thisrefers to the current context object. In module scope,thisrefers tomodule.exports. Inside functions,thisdepends on how the function is called. -
21. What is the Node.js buffer?
A Buffer is a temporary storage for raw binary data. Unlike JavaScript strings, Buffers can't be resized. They're used for handling binary data streams and file operations.
const buf = Buffer.from('Hello', 'utf8'); console.log(buf); -
22. What is the difference between blocking and non-blocking code?
Blocking code waits for an operation to complete before proceeding. Non-blocking code initiates an operation and continues immediately, handling results via callbacks or Promises.
-
23. What is the callback queue?
The callback queue (also called task queue) holds callbacks waiting to be executed. The event loop checks it after the call stack is empty and executes callbacks one by one.
-
24. What is the microtask queue?
The microtask queue has higher priority than the callback queue. It includes Promise callbacks and
process.nextTick(). The event loop processes all microtasks before moving to the callback queue. -
25. Explain the difference between
process.nextTick()andsetImmediate().process.nextTick()queues a callback in the microtask queue (executed first), whilesetImmediate()queues in the callback queue. Therefore,process.nextTick()executes beforesetImmediate().setImmediate(() => console.log('immediate')); process.nextTick(() => console.log('nextTick')); // Output: nextTick, immediate -
26. What is middleware in Express?
Middleware is a function that has access to request and response objects. It can modify them, end the request, or pass control to the next middleware using
next(). -
27. What is dependency injection?
Dependency injection is a design pattern where dependencies are passed to a function or class rather than created internally. It improves testability and modularity.
-
28. What is the purpose of
module.exportsandrequire()?module.exportsexports functionality from a module, whilerequire()imports it into another module. This is the module system that enables code reusability and organization. -
29. What is the difference between default export and named export?
Default export (
export default) exports one main value per module, imported without braces. Named exports (export) export multiple values, imported with braces or aliased. -
30. What is hoisting in Node.js?
Hoisting moves variable and function declarations to the top of their scope before execution.
vardeclarations are hoisted and initialized withundefined, whileletandconstare hoisted but not initialized.
Modules & Packages (31-45)
-
31. How do you create a module in Node.js?
Create a JavaScript file and use
module.exportsto export functionality:// math.js module.exports = { add: (a, b) => a + b, subtract: (a, b) => a - b }; -
32. What are built-in modules in Node.js?
Built-in modules are pre-installed with Node.js, including
fs,path,http,util,events,stream,crypto, andos. They don't require installation via npm. -
33. Explain the
require()function.require()loads and executes a module, returningmodule.exports. It caches modules, so subsequent calls return the cached module. Syntax:const module = require('./path'); -
34. What is the difference between absolute and relative paths in
require()?Absolute paths start with
/or a module name (loaded from node_modules). Relative paths start with./or../and are relative to the current file's directory. -
35. What are npm scripts?
npm scripts are commands defined in package.json that automate tasks. Common scripts:
start,test,build. Run withnpm run scriptname.{ "scripts": { "start": "node app.js", "test": "jest", "dev": "nodemon app.js" } } -
36. What is package-lock.json?
package-lock.json locks specific versions of dependencies for reproducible installations. It ensures all developers and CI/CD systems use identical dependency versions.
-
37. What is the difference between
--save,--save-dev, and global installation?-
--saveadds to dependencies (production) -
--save-devadds to devDependencies (development only) - Global installs make the package available system-wide
-
-
38. What is semantic versioning?
Semantic versioning (semver) uses format MAJOR.MINOR.PATCH (e.g., 1.2.3):
- MAJOR: Breaking changes
- MINOR: Backward-compatible features
- PATCH: Bug fixes
-
39. How do you resolve module name conflicts?
Use aliasing with require:
const express = require('express')or use different import names. In ES6 modules, useimport * as alias from 'module'. -
40. What is module caching in Node.js?
Node.js caches modules after first load. Subsequent requires return the cached module without re-executing the code. This improves performance but means module state persists.
-
41. How do you clear the module cache?
Use
delete require.cache[require.resolve('./module')]to remove a module from cache, forcing a fresh load on next require. -
42. What is the purpose of node_modules directory?
node_modules stores all installed packages and their dependencies. npm automatically resolves and installs all required packages here based on package.json specifications.
-
43. Explain the npm dependency tree.
npm organizes dependencies hierarchically. Each package can have its own node_modules with subdependencies. npm v3+ uses flat structure to reduce duplication but may have conflicts.
-
44. What is the purpose of .npmrc file?
.npmrc contains npm configuration settings. It can specify registry URLs, authentication tokens, log levels, and other npm behavior preferences.
-
45. How do you publish a package to npm?
- Create a package.json with unique name
- Add code and documentation
- Create npm account
- Run
npm login - Run
npm publish
Asynchronous Programming (46-60)
-
46. Explain Promises and their lifecycle.
Promises have three states:
- Pending: Initial state, operation hasn't completed.
- Fulfilled: Operation successful, has a value.
- Rejected: Operation failed, has a reason.
const promise = new Promise((resolve, reject) => { setTimeout(() => resolve('Done'), 1000); }); -
47. What is
Promise.all()?Promise.all()takes an array of Promises and returns a single Promise that resolves when all input Promises resolve, or rejects if any rejects.Promise.all([promise1, promise2, promise3]) .then(results => console.log(results)) .catch(error => console.log(error)); -
48. What is
Promise.race()?Promise.race()returns a Promise that settles as soon as the first input Promise settles (resolves or rejects).Promise.race([promise1, promise2]) .then(result => console.log(result)); -
49. What is
Promise.allSettled()?Promise.allSettled()waits for all Promises to settle (fulfill or reject) and returns an array of results with status and value/reason. -
50. What is
Promise.any()?Promise.any()returns a Promise that resolves as soon as one input Promise resolves, or rejects only if all Promises reject. -
51. Explain async/await execution flow.
When an async function encounters
await, it pauses and returns a Promise. The next line executes only when the awaited Promise settles. This makes asynchronous code appear synchronous.async function example() { console.log('Start'); await new Promise(r => setTimeout(r, 1000)); console.log('After 1 second'); } -
52. What is the difference between
then()andawait?then()is chainable and returns immediately (with a Promise), whileawaitblocks execution.awaitis cleaner for sequential operations,then()is better for parallel operations with chains. -
53. How do you handle errors with Promises?
Use
.catch()method ortry/catchwith async/await:// Promises promise.then(result => {}).catch(error => {}); // Async/await try { const result = await promise; } catch(error) { console.log(error); } -
54. What is callback function in Node.js?
A callback is a function passed to another function, executed after an operation. The convention is the last parameter, often with error as first parameter (error-first callback).
function readFile(path, callback) { fs.readFile(path, (err, data) => { if (err) callback(err); else callback(null, data); }); } -
55. What is the event emitter pattern?
EventEmitter is a class where objects can emit events and listeners can subscribe to them. It's central to Node.js's event-driven architecture.
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('event', () => console.log('Event occurred')); emitter.emit('event'); -
56. Explain the observer pattern in Node.js.
The observer pattern defines a one-to-many relationship where multiple observers listen to a subject. When the subject changes, all observers are notified. EventEmitter implements this pattern.
-
57. What is the purpose of
setTimeout()in Node.js?setTimeout()schedules code to run after a specified delay (in milliseconds). It's non-blocking—code continues executing while the timer runs. -
57. What is the purpose of
setTimeout()in Node.js?setTimeout()schedules code to run after a specified delay (in milliseconds). It's non-blocking—code continues executing while the timer runs. -
58. What is the difference between
setImmediate()andsetTimeout()?setTimeout(fn, 0)adds callback to timer phase of event loop (after poll), whilesetImmediate()adds to check phase (after poll).setImmediate()usually runs first. -
59. What is
setInterval()?setInterval()repeatedly executes code at specified intervals. Returns an interval ID used withclearInterval()to stop the interval. -
60. Explain the concept of backpressure in Node.js.
Backpressure occurs when the readable stream produces data faster than writable stream consumes it. Handle with
pause(),resume(), or checkwrite()return value.
Events & Streams (61-75)
-
61. What is an EventEmitter?
EventEmitter is a Node.js class for implementing the observer pattern. Objects that inherit from EventEmitter can emit events and listeners can subscribe to them.
const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); -
62. Explain the common EventEmitter methods.
-
on(event, listener)Add listener -
once(event, listener)Add one-time listener -
off(event, listener)Remove listener -
emit(event, [...args])Emit event -
listeners(event)Get listeners array -
removeAllListeners()Remove all listeners
-
-
63. What is a stream in Node.js?
A stream is an object that lets you read data from a source or write data to a destination in chunks. Streams are memory-efficient for large data volumes.
-
64. What are the types of streams?
There are four types of streams in Node.js:
-
Readable: Data source (reading files, receiving requests) -
Writable: Data destination (writing files, sending responses) -
Duplex: Both readable and writable (sockets) -
Transform: Modify data while reading/writing (compression, encryption)
-
-
65. What is the purpose of
fs.createReadStream()?Creates a readable stream for reading files in chunks. More memory-efficient than
fs.readFile()for large files.const stream = fs.createReadStream('large-file.txt'); stream.on('data', chunk => console.log(chunk)); stream.on('end', () => console.log('Stream ended')); -
66. What is the purpose of
fs.createWriteStream()?Creates a writable stream for writing files in chunks. Prevents memory issues when writing large amounts of data.
const stream = fs.createWriteStream('output.txt'); stream.write('Hello '); stream.write('World'); stream.end(); -
67. What is piping in Node.js?
Piping connects a readable stream's output directly to a writable stream's input. It automatically handles backpressure and data chunking.
fs.createReadStream('input.txt') .pipe(fs.createWriteStream('output.txt')); -
68. Explain the
pipe()method.pipe()connects readable and writable streams, forwarding data automatically. Returns the destination stream for chaining.readable.pipe(transform).pipe(writable); -
69. What is a transform stream?
A transform stream modifies data while reading or writing. Examples include compression (zlib), encryption, and data parsing.
const zlib = require('zlib'); fs.createReadStream('input.txt') .pipe(zlib.createGzip()) .pipe(fs.createWriteStream('input.txt.gz')); -
70. What is the
once()method in EventEmitter?once()adds a listener that fires only once, then removes itself automatically.emitter.once('connection', () => { console.log('Connection established once'); }); -
71. Explain the difference between
on()andonce().on()adds a persistent listener that fires every time the event occurs.once()adds a temporary listener that fires only once then removes itself. -
72. What is the purpose of the
removeListener()method?removeListener()removes a specific listener from an event, preventing it from firing on that event.const callback = () => console.log('Event'); emitter.on('event', callback); emitter.removeListener('event', callback); -
73. What is
removeAllListeners()?removeAllListeners()removes all listeners for a specific event (or all events if none specified).emitter.removeAllListeners('event'); emitter.removeAllListeners(); // Removes all listeners for all events -
74. How do you handle stream errors?
Listen to the
errorevent on streams:stream.on('error', (error) => { console.log('Stream error:', error); }); -
75. What is the
flowingmode in streams?In flowing mode, stream automatically emits
dataevents. In paused mode, you must explicitly callread(). Switch withresume()andpause().
File System (76-85)
-
76. What is the
fsmodule?The fs (file system) module provides functions for working with files and directories. It offers both synchronous and asynchronous methods.
-
77. Explain the difference between
fs.readFile()andfs.readFileSync().fs.readFile()is asynchronous (non-blocking) and accepts a callback, whilefs.readFileSync()is synchronous (blocking) and returns data immediately. Async is preferred for better performance.// Async fs.readFile('file.txt', 'utf8', (err, data) => { console.log(data); }); // Sync const data = fs.readFileSync('file.txt', 'utf8'); -
78. Explain the difference between
fs.writeFile()andfs.appendFile().fs.writeFile()overwrites file completely, whilefs.appendFile()appends content to the end without removing existing data. -
79. How do you delete a file in Node.js?
Use
fs.unlink()(async) orfs.unlinkSync()(sync):fs.unlink('file.txt', (err) => { if (err) console.log(err); else console.log('File deleted'); }); -
80. What is
fs.stat()used for?fs.stat()returns file/directory statistics (size, creation time, modification time, permissions, etc.) as a Stats object.fs.stat('file.txt', (err, stats) => { console.log(stats.size, stats.isFile(), stats.isDirectory()); }); -
81. How do you check if a file exists?
Use
fs.existsSync()for sync check orfs.access()for async check:if (fs.existsSync('file.txt')) console.log('Exists'); fs.access('file.txt', fs.constants.F_OK, (err) => { if (!err) console.log('File exists'); }); -
82. What is
fs.watch()?fs.watch()watches for changes in a file or directory and fires callbacks when changes occur. Useful for auto-reloading during development.fs.watch('file.txt', (eventType, filename) => { console.log(`${eventType}: ${filename}`); }); -
83. How do you create a directory in Node.js?
Use
fs.mkdir()(async) orfs.mkdirSync()(sync):fs.mkdir('new-folder', { recursive: true }, (err) => { if (err) console.log(err); }); -
84. How do you read a directory?
Use
fs.readdir()to list files and subdirectories:fs.readdir('./', (err, files) => { files.forEach(file => console.log(file)); }); -
85. What is the
pathmodule?The path module provides utilities for working with file and directory paths across different operating systems. Methods include
path.join(),path.resolve(),path.basename(),path.dirname(), etc.
HTTP & Networking (86-100)
-
86. What is the
httpmodule?The http module creates HTTP servers and clients. It provides the
createServer()method to build web servers and enables handling requests and responses.const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World'); }); server.listen(3000); -
87. Explain the request and response objects.
The request object represents incoming HTTP requests with properties like method, url, headers, and methods like
on()to read data. The response object represents the outgoing response with methods likewriteHead(),write(), andend(). -
88. What is
res.writeHead()?res.writeHead()writes HTTP status code and response headers. Must be called beforewrite()orend().res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }); -
89. What is the difference between
res.write()andres.end()?res.write()writes chunks of response body, can be called multiple times.res.end()writes final chunk and signals response completion.res.write('Hello '); res.write('World'); res.end(); // Response sent -
90. How do you handle different HTTP methods?
Check
req.methodto determine HTTP method and handle accordingly:if (req.method === 'GET') { // Handle GET } else if (req.method === 'POST') { // Handle POST } -
91. What is routing in Node.js?
Routing maps URLs to handler functions. In Express:
app.get('/path', handler). In raw Node.js: checkreq.urlandreq.methodto determine route. -
92. What is CORS?
CORS (Cross-Origin Resource Sharing) controls whether resources can be accessed from different origins. Set
Access-Control-Allow-Originheader to allow cross-origin requests. -
93. What is the
urlmodule?The url module parses and formats URL strings. Methods include
url.parse()(parse URL),url.format()(format URL object), andurl.resolve()(resolve relative URLs). -
94. What is the
querystringmodule?The querystring module parses and formats URL query strings.
querystring.parse()converts query string to object,querystring.stringify()converts object to query string. -
95. Explain the purpose of middleware in Express.
Middleware processes requests before responses. Middleware functions have access to request, response, and next middleware. Use for authentication, logging, parsing, etc.
-
96. What is
app.use()?app.use()registers middleware that runs for every request. Middleware is executed in order and can modify request/response or callnext()to continue.app.use((req, res, next) => { console.log('Request received'); next(); }); -
97. What is
next()in middleware?next()passes control to the next middleware or route handler. If not called, request processing stops. -
98. Explain the purpose of body parsing middleware.
Body parsing middleware (like
express.json()) reads request body and parses it (JSON, URL-encoded, etc.) intoreq.bodyfor easy access.app.use(express.json()); app.post('/api/data', (req, res) => { console.log(req.body); // Parsed JSON }); -
99. What is
res.json()?res.json()automatically serializes data to JSON and sends it with appropriate headers.res.json({ message: 'Success', data: [1, 2, 3] }); -
100. What is the purpose of status codes?
HTTP status codes indicate request result:
- 2xx: Success (200, 201, 204)
- 3xx: Redirect (301, 302, 304)
- 4xx: Client error (400, 401, 403, 404)
- 5xx: Server error (500, 502, 503)
Notes
- That's a complete set of 120 Node.js interview questions with concise answers, organized across Basics & Fundamentals, Core Concepts, Modules & Packages, Asynchronous Programming, Events & Streams, File System and HTTP & Networking.