Here’s a list of 20 Node.js interview questions, covering both basic and advanced topics for a comprehensive preparation:
Basic Questions
-
What is Node.js, and why is it used?
- Node.js is a server-side runtime environment based on the V8 JavaScript engine, used for building fast and scalable network applications.
-
Explain the event loop in Node.js.
- The event loop is the mechanism that handles asynchronous callbacks in a single thread by delegating tasks to the system and processing them as events return.
-
What are streams in Node.js?
- Streams are objects used for reading or writing continuous chunks of data. Types include:
- Readable (e.g., file read streams)
- Writable (e.g., file write streams)
- Duplex (e.g., sockets)
- Transform (e.g., zlib for compression).
- Streams are objects used for reading or writing continuous chunks of data. Types include:
-
What is the difference between
setImmediate()
andprocess.nextTick()
?-
setImmediate()
: Executes after the current event loop completes. -
process.nextTick()
: Executes before the next event loop iteration begins.
-
-
How does Node.js handle concurrency?
- Node.js uses an event-driven, non-blocking I/O model via the event loop. Heavy computations are offloaded to worker threads or background processes.
-
How do you handle uncaught exceptions in Node.js?
- Use the
process.on('uncaughtException', callback)
event to handle uncaught exceptions, but it's recommended to exit the process after logging the error.
- Use the
Intermediate Questions
-
What is middleware in Node.js? Provide an example.
- Middleware functions in frameworks like Express.js process requests and responses.
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Middleware executed');
next(); // Passes control to the next middleware/route handler
});
app.get('/', (req, res) => res.send('Hello World'));
app.listen(3000);
-
How do you manage environment variables in Node.js?
- Use the
dotenv
package to load environment variables from a.env
file:
- Use the
require('dotenv').config();
console.log(process.env.MY_VARIABLE);
-
What are worker threads in Node.js?
- Worker threads are used to execute CPU-intensive JavaScript code in parallel, enabling better performance for heavy computations:
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
-
Explain the cluster module in Node.js.
- The cluster module allows Node.js to spawn multiple processes (workers) sharing the same server port to leverage multi-core CPUs:
const cluster = require('cluster'); const http = require('http'); if (cluster.isMaster) { cluster.fork(); // Create worker processes } else { http.createServer((req, res) => res.end('Hello')).listen(8000); }
-
What is the difference between blocking and non-blocking I/O?
-
Blocking I/O: Operations that block the event loop until completion (e.g.,
fs.readFileSync
). -
Non-blocking I/O: Operations that allow the event loop to continue while waiting for execution (e.g.,
fs.readFile
).
-
Blocking I/O: Operations that block the event loop until completion (e.g.,
-
What is the
libuv
library in Node.js?-
libuv
is a C library used by Node.js to handle the event loop, asynchronous I/O, and thread pool.
-
Advanced Questions
-
What are the differences between
spawn()
,fork()
, andexec()
in thechild_process
module?-
spawn()
: Executes a command and streams the output. -
fork()
: Spawns a new Node.js process for IPC (Inter-Process Communication). -
exec()
: Executes a command and buffers the output.
-
-
What is the purpose of the
cluster
module in scaling Node.js applications?- The
cluster
module enables horizontal scaling by creating worker processes to handle concurrent requests using multi-core CPUs.
- The
-
What is the difference between
req.params
,req.query
, andreq.body
in Express.js?-
req.params
: Retrieves route parameters (e.g.,/users/:id
). -
req.query
: Retrieves query string parameters (e.g.,/users?id=123
). -
req.body
: Retrieves payload data from POST/PUT requests.
-
-
How do you secure a Node.js application?
- Use HTTPS.
- Validate and sanitize inputs to prevent SQL injection and XSS.
- Implement rate limiting to prevent brute force attacks.
- Use libraries like
helmet
for HTTP header security.
-
What are memory leaks in Node.js, and how can you debug them?
- Memory leaks occur when objects are no longer needed but not garbage-collected. Tools like
node --inspect
, Chrome DevTools, orheapdump
can help identify leaks.
- Memory leaks occur when objects are no longer needed but not garbage-collected. Tools like
-
What is event emitter, and how is it used in Node.js?
- The
EventEmitter
class allows objects to subscribe to and emit events:
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('event', () => console.log('Event triggered')); emitter.emit('event');
- The
-
How does Node.js handle large file uploads efficiently?
- By using streams, Node.js processes chunks of data rather than loading the entire file into memory:
const fs = require('fs'); const server = require('http').createServer((req, res) => { req.pipe(fs.createWriteStream('file.txt')); res.end('Upload complete'); }).listen(3000);
-
Explain the role of
package-lock.json
and why it is important.-
package-lock.json
locks dependency versions to ensure consistent installs across environments, improving reproducibility and avoiding unexpected issues.
-
Bonus Topics
- Explain how you would implement WebSockets in Node.js.
- Discuss the advantages and challenges of serverless with Node.js.
- Implement a custom middleware in Express.js.
Top comments (0)