Node.js interview questions commonly cover the JavaScript runtime, the event loop, asynchronous programming, modules, npm, HTTP servers, databases, streams, security, and production diagnostics. The questions and answers below are organized for freshers, intermediate developers, and experienced Node.js candidates.
- Entry-level Node.js interview questions
- Intermediate Node.js interview questions
- Advanced Node.js interview questions
- Node.js interview preparation FAQs
Entry-Level Node.js Interview Questions for Freshers
What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime built on the V8 JavaScript engine. It enables JavaScript programs to run outside a web browser. Node.js is commonly used for web servers, APIs, command-line tools, real-time applications, automation, and data-processing services.
- Open source: Its source code is publicly available.
- Cross-platform: It runs on Windows, macOS, Linux, and other supported systems.
- Asynchronous: Many Node.js APIs provide non-blocking operations.
- Event-driven: Events and callbacks are central to its programming model.
- JavaScript runtime: It executes JavaScript outside the browser.
Which programming language is used for Node.js applications?
Node.js applications are primarily written in JavaScript. Developers can also use TypeScript and compile it to JavaScript before execution.
How is Node.js different from traditional server-side frameworks?
Node.js normally executes JavaScript on a main event-loop thread and delegates many I/O operations to the operating system or its supporting worker pool. Instead of assigning one application thread to every connection, it can manage many concurrent I/O operations through events and callbacks. Node.js is not literally single-threaded in every respect: worker threads, child processes, the runtime, and native libraries may use additional threads.
What are the main features of Node.js?
- Asynchronous, event-driven APIs
- Non-blocking I/O for many network and file operations
- JavaScript execution through the V8 engine
- A standard library for HTTP, files, streams, processes, cryptography, and other tasks
- A large package ecosystem accessed through npm
- Support for CommonJS and ECMAScript modules
- Streams for processing data incrementally
How does event-driven programming work in Node.js?
An application registers handlers for events or asynchronous results. When an operation such as a network request or file read starts, Node.js can continue processing other work instead of waiting for that operation to finish. When the operation completes, its callback, promise reaction, or event handler is queued for execution. The event loop coordinates when eligible JavaScript callbacks run.
What is the MEAN stack, and where does Node.js fit?
MEAN is a JavaScript-oriented application stack. Its commonly cited components are:
- MongoDB for document-oriented data storage
- Express for the web application and API layer
- Angular for the browser-based user interface
- Node.js as the server-side JavaScript runtime
What is npm?
npm is the package manager distributed with Node.js. It includes a command-line client and access to the npm package registry. A project’s package.json file records metadata, scripts, dependencies, and development dependencies.
How do you install, update, and uninstall an npm package?
Run npm commands from the project directory. Local installation is the default. The global -g option is generally reserved for command-line tools that need to be available from multiple directories.
npm install <package>
npm install --save-dev <package>
npm update <package>
npm uninstall <package>
npm install -g <package>
What is the difference between dependencies and devDependencies?
dependencies are packages required when the application runs. devDependencies are normally needed only for development tasks such as testing, linting, formatting, compilation, or local tooling. The actual classification depends on how the application is built and deployed.
How do CommonJS and ECMAScript modules import code?
CommonJS uses require() and module.exports. ECMAScript modules use import and export. The module system is determined by factors such as file extensions and the type field in package.json.
This CommonJS example imports the built-in fs module:
var fs = require('fs');
import { readFile } from 'node:fs';
What is a callback in Node.js?
A callback is a function passed to another function so that it can be invoked later. Many traditional Node.js APIs use an error-first callback convention in which the first argument contains an error or null, while later arguments contain the result.
var fs = require('fs');
// read file sample.txt
fs.readFile('sample.txt',
// callback function that is called when reading file is done
function(err, data) {
if (err) throw err;
// data is a buffer containing file content
console.log("Reading file completed : " + new Date().toISOString());
});
console.log("After readFile asynchronously : " + new Date().toISOString());
Reference: Node.js – Callback Function
What is callback hell, and how can it be avoided?
Callback hell describes deeply nested callbacks that make control flow and error handling difficult to follow. It can be reduced by using small named functions, promises, async/await, or appropriate control-flow utilities. Extracting related operations into separate modules also improves testability.
What is a Promise in Node.js?
A Promise represents the eventual completion or failure of an asynchronous operation. It can be pending, fulfilled, or rejected. Consumers attach handlers with then(), catch(), and finally(), or await the promise inside an async function.
What does async/await do in Node.js?
An async function always returns a promise. The await keyword pauses that function until a promise settles without blocking the entire Node.js process. Rejections should be handled with try/catch or propagated to the caller.
import { readFile } from 'node:fs/promises';
async function loadConfig() {
try {
const text = await readFile('config.json', 'utf8');
return JSON.parse(text);
} catch (error) {
console.error('Unable to load configuration:', error.message);
throw error;
}
}
Which Node.js module is used for file operations?
The built-in fs module provides callback-based and synchronous file-system APIs. Promise-based operations are available from fs/promises.
var fs = require('fs');
fs.readFile()fs.writeFile()fs.appendFile()fs.open()fs.rename()fs.unlink()
Synchronous variants are available, but synchronous file operations block the event-loop thread and should be used carefully in servers.
What is a Buffer in Node.js?
A Buffer represents a fixed-length sequence of bytes. It is used for binary data from files, TCP connections, cryptographic operations, and other byte-oriented sources. Text can be converted to and from buffers by specifying an encoding such as UTF-8.
How do you create an HTTP server in Node.js?
The built-in http module can create a server without an external web framework. A request listener receives request and response objects for each incoming request.
// include http module in the file
var http = require('http');
// create a server
http.createServer(function (req, res) {
// http header
// 200 - is the OK message
// to respond with html content, 'Content-Type' should be 'text/html'
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Node.js says hello!'); //write a response to the client
res.end(); //end the response
}).listen(9000); //the server object listens on port 9000
Reference: Node.js – Create HTTP Web Server
Intermediate Node.js Interview Questions and Answers
What is the Node.js event loop?
The event loop coordinates the execution of callbacks after timers, I/O operations, and other asynchronous work become ready. Its phases handle categories of callbacks such as timers, pending callbacks, polling, checking, and close callbacks. A strong interview answer should distinguish the event loop from the operating-system facilities and worker pool that perform or monitor some underlying operations.
What is the difference between process.nextTick(), queueMicrotask(), setImmediate(), and setTimeout()?
process.nextTick()schedules a callback in Node.js’s next-tick queue, which is processed before the event loop continues.queueMicrotask()schedules a standard microtask.setImmediate()schedules work for the check phase of a later event-loop iteration.setTimeout(fn, 0)schedules a timer after its minimum threshold; it does not guarantee immediate execution.
Excessive next-tick or microtask scheduling can delay I/O because the associated queues may keep receiving more work.
What are streams in Node.js?
Streams process data incrementally instead of requiring the complete value in memory. The four fundamental stream types are Readable, Writable, Duplex, and Transform. Files, HTTP messages, compression utilities, and TCP sockets use stream interfaces.
What is backpressure in Node.js streams?
Backpressure occurs when a data producer is faster than its consumer. Node.js streams communicate this condition so that the producer can slow down. Using pipe() or pipeline() usually handles flow control more safely than manually forwarding every data chunk.
What is chaining in Node.js?
Method chaining is possible when a method returns an object that provides the next method. It is an API design pattern rather than behavior automatically supplied by every Node.js module. The following historical placeholder illustrates the shape of a chain but is not executable because var is a reserved keyword and the methods are undefined:
var.someFunction().anotherFunction().someAnotherFunc();
How should a Node.js process be stopped?
For an orderly shutdown, stop accepting new requests, finish or time out active work, close database connections, and set an appropriate exit code. Calling process.exit() terminates the process immediately and may prevent pending output or cleanup from completing. The following statement demonstrates immediate termination with a non-zero status:
process.exit(-1);
In application code, process.exitCode = 1 is often preferable when the process can be allowed to finish naturally.
How should errors be handled in a Node.js application?
- Check the error argument in callback-based APIs.
- Use
try/catcharound awaited promise operations. - Return rejected promises instead of hiding failures.
- Use centralized error middleware in frameworks such as Express.
- Log useful context without exposing passwords, tokens, or personal data.
- Treat uncaught exceptions and unhandled rejections as serious faults; record the failure and shut down safely when application state may be unreliable.
How do you redirect a URL with the Node.js HTTP module?
A redirect response contains a 3xx status code and a Location header. Use 301 or 308 only when the move is intended to be permanent; 302, 303, or 307 may be suitable for temporary or method-sensitive redirects.
The following existing example demonstrates a 301 response. In production, avoid constructing trusted destinations from an unvalidated Host header, and do not map arbitrary request paths directly to files.
var http = require('http');
var fs = require('fs');
// create a http server
http.createServer(function (req, res) {
if (req.url == '/page-c.html') {
// redirect to page-b.html with 301 (Moved Permanently) HTTP code in the response
res.writeHead(301, { "Location": "http://" + req.headers['host'] + '/page-b.html' });
return res.end();
} else {
// for other URLs, try responding with the page
console.log(req.url)
// read requested file
fs.readFile(req.url.substring(1),
function(err, data) {
if (err) throw err;
res.writeHead(200);
res.write(data.toString('utf8'));
return res.end();
});
}
}).listen(8085);
How do you connect a Node.js application to MySQL?
Install a maintained MySQL client library, load connection settings from protected configuration, and normally use a connection pool. Parameterized queries should be used for values supplied by users. Do not commit database passwords to source control.
- Install and import the database client.
- Configure the host, port, user, password, and database.
- Create a connection or pool.
- Connect and handle connection errors.
- Execute parameterized queries and release pooled connections correctly.
This older CommonJS example shows the basic connection sequence:
// include mysql module
var mysql = require('mysql');
// create a connection variable with the details required
var con = mysql.createConnection({
host: "localhost", // ip address of server running mysql
user: "arjun", // user name to your mysql database
password: "password" // corresponding password
});
// connect to the database.
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Reference: Node.js – Connect to MySQL Database
What is a result object in Node.js MySQL code?
A database client supplies the query result to a callback or resolves a promise with it. For a SELECT query, the result generally contains rows. For an INSERT, UPDATE, or DELETE, it may contain metadata such as an inserted identifier or affected-row count. Exact properties depend on the client library and query type.
What is Express.js, and how does it relate to Node.js?
Express is a web framework that runs on Node.js. It provides routing, middleware composition, request and response helpers, and error-handling conventions. Node.js supplies the runtime and low-level HTTP APIs; Express adds application-level abstractions.
What is Express middleware?
Middleware is a function that participates in the request-response cycle. It can inspect or modify request and response objects, end the response, report an error, or call next() to pass control onward. Ordering matters because Express runs matching middleware in registration order.
How do you add functionality to a Node.js module?
For application-owned modules, define and export the required functions explicitly. Avoid modifying a shared built-in module object because the mutation can affect other consumers in the same process. The following legacy example demonstrates object mutation and re-exporting, but a wrapper module is safer for production code.
// include the module that you like extend
var fs = require('fs');
// add a new function, printMessage(), to the module
fs.printMessage = function(str){
console.log("Message from newly added function to the module");
console.log(str);
}
// re-export the module for changes to take effect
module.exports = fs
// you may use the newly added function
fs.printMessage("Success");
Reference: Node.js – Add new functions to module
Should built-in Node.js module functions be overridden?
Overriding a function on a shared built-in module is generally unsuitable for production applications. It creates global side effects, breaks expected behavior, and makes upgrades and tests harder to reason about. Prefer a wrapper function, dependency injection, or test mocking. The following legacy example illustrates replacement of a property and should not be treated as a recommended file-system implementation:
// include the module whose functions are to be overridden
var fs = require('fs');
// delete the function you would like to override
delete fs['readFile'];
// add new functional with the same name as deleted function
fs.readFile = function(str){
console.log("The functionality has been overridden.");
console.log(str);
}
// re-export the module for changes to take effect
module.exports = fs
// you may use the newly overriden function
fs.readFile("sample.txt");
Reference: Node.js – Override functions of a module
Advanced Node.js Interview Questions for Experienced Developers
Why can CPU-intensive work reduce Node.js server throughput?
Long-running JavaScript computations occupy the event-loop thread, delaying timers, request handlers, and completed I/O callbacks. CPU-heavy work can be split into smaller units, moved to worker threads, delegated to another process or service, or handled through a job queue. The appropriate choice depends on latency, isolation, data-transfer cost, and operational requirements.
What is the difference between worker_threads, child_process, and cluster?
worker_threadsruns JavaScript in additional threads within one process and can share memory deliberately.child_processstarts separate operating-system processes and communicates through pipes or inter-process messaging.clustercreates Node.js worker processes that can share a server port. Many deployments instead run multiple application instances through a process manager or container platform.
How would you diagnose event-loop lag?
Measure event-loop delay, CPU utilization, request latency, garbage collection, memory growth, and slow external calls. Capture CPU profiles or diagnostic reports during representative load. Common causes include synchronous APIs in request paths, expensive serialization, large regular-expression workloads, excessive logging, unbounded loops, and callbacks that perform too much work.
What causes memory leaks in Node.js applications?
A memory leak occurs when objects remain reachable even though the application no longer needs them. Typical causes include unbounded caches, event listeners that are never removed, timers retaining closures, global collections, unresolved work, and references held by long-lived objects. Heap snapshots taken at different times can help identify growing object groups and their retaining paths.
How should production Node.js applications handle graceful shutdown?
- Listen for the termination signals used by the deployment environment.
- Mark the instance as unavailable for new traffic.
- Stop accepting new connections.
- Allow active requests and background jobs to finish within a deadline.
- Close database pools, queues, and other resources.
- Exit with a meaningful status after cleanup, or force termination after the deadline.
How do you secure dependencies in a Node.js project?
- Commit the appropriate lockfile and use reproducible installation commands in automation.
- Review dependency audit reports and verify whether a reported issue affects the application’s actual usage.
- Update Node.js and direct dependencies through a tested maintenance process.
- Remove unused packages and avoid packages with unclear ownership or unnecessary privileges.
- Review install scripts before adopting unfamiliar packages.
- Protect registry credentials and use short-lived or narrowly scoped tokens where supported.
- Generate a software bill of materials when required by the deployment or compliance process.
npm ci
npm audit
npm outdated
An audit command is a diagnostic aid, not a substitute for evaluating exploitability, release notes, tests, and operational impact.
How should secrets and user input be handled in Node.js APIs?
Keep secrets outside source code, restrict their access, and rotate them when required. Validate request data against explicit schemas, enforce size limits, use parameterized database queries, and encode output for its destination. Apply authentication, authorization, rate controls, secure transport, and carefully configured HTTP headers according to the application’s threat model.
How do you test asynchronous Node.js code?
Return or await the promise created by the code under test so that the test runner knows when work finishes. Test resolved values, rejected promises, timeouts, cleanup, and partial failures. External services can be replaced at a clear boundary, but excessive mocking can hide integration problems. Combine focused unit tests with integration tests for routes, databases, and message handlers.
What should an experienced candidate explain about API performance?
A complete answer should discuss measurement before optimization. Relevant areas include database query plans and indexes, connection pooling, response size, serialization cost, caching and invalidation, stream backpressure, external-service timeouts, bounded concurrency, event-loop delay, memory behavior, and horizontal scaling. Performance changes should be checked with representative workloads and observable service-level metrics.
Node.js Interview Preparation FAQs
Which Node.js topics should freshers prepare first?
Start with the runtime, modules, npm, callbacks, promises, async/await, the event loop, buffers, streams, HTTP, Express routing, middleware, error handling, and basic database access. Be ready to write and explain a small asynchronous program.
Which Node.js interview topics are common for experienced developers?
Experienced interviews often examine event-loop behavior, stream backpressure, worker threads and processes, API design, authentication and authorization, dependency security, graceful shutdown, observability, memory leaks, performance diagnosis, testing strategy, and production incident decisions.
Are Express.js and MongoDB questions part of a Node.js interview?
They may be included when the role uses an Express and MongoDB stack. Node.js itself does not require either technology, so candidates should distinguish runtime concepts from framework and database concepts.
Should interview answers use callbacks or async/await?
Use the style requested by the interviewer. For new application code, promises and async/await often make sequential asynchronous flows easier to read. Candidates should still understand error-first callbacks because many Node.js APIs and existing projects use them.
How should a candidate explain that Node.js is single-threaded?
Say that JavaScript normally runs on a main event-loop thread in each Node.js process, while the runtime can use operating-system asynchronous facilities and supporting threads. Applications can also create worker threads or child processes. This is more accurate than saying the entire Node.js runtime uses only one thread.
Node.js Interview Content QA Checklist
- Confirm that answers distinguish the JavaScript event-loop thread from worker threads, the worker pool, and child processes.
- Check that npm examples use valid local and global installation options.
- Verify that callback, promise, and
async/awaitexamples include meaningful error handling. - Keep Express.js and MongoDB concepts separate from features provided directly by Node.js.
- Review HTTP redirect examples for correct status-code semantics and untrusted-header handling.
- Check database examples for protected credentials, parameterized queries, and connection cleanup.
- Ensure production answers cover graceful shutdown, dependency maintenance, observability, and event-loop blocking.
TutorialKart.com