Node JS has become a cornerstone of modern backend development, powering everything from real‑time chat applications to large‑scale APIs. Its efficient, event‑driven architecture allows developers to build high‑performance services using JavaScript on the server. Whether you are a backend engineer, full‑stack developer, or DevOps professional, you will often face questions that test your understanding of Node JS Developer fundamentals, asynchronous patterns, APIs, testing strategies, performance optimisations, and security best practices.
This guide presents the top fifty Node JS interview questions organised into five focused sections. Each question includes a clear answer and, where helpful, brief code examples. You should attempt each question in your development environment before reading the solution. By following this structured approach, you will strengthen your practical skills and gain the confidence needed to demonstrate your expertise in any technical interview.
Who Should Read This Guide
This guide is designed for anyone who will work with Node JS in a technical interview. You will find it most useful if you are:
- Node JS Developer and Backend Developers building server‑side applications with JavaScript
- Full‑Stack Engineers who write both client and server code in Node JS
- DevOps Professionals automating deployment and monitoring tasks using Node JS tools
- Students and Graduates preparing for roles that require a strong understanding of Node JS fundamentals
If you plan to develop APIs, real‑time applications, or microservices with Node JS, this guide will help you focus on the most common topics and practise clear, concise answers before your interview.
Core JavaScript, Modules & Package Management | Node JS Developer
1. What is Node js and how does it differ from browser JavaScript?
- Node js is a runtime that executes JavaScript on the server, built on Chrome’s V8 engine.
- Unlike browser JavaScript, it provides APIs for file I/O, networking and process management.
2. Explain the event loop and its phases.
- The event loop handles asynchronous callbacks in cycles called ticks.
- Key phases include timers (scheduled callbacks), I/O callbacks, idle/prepare, poll (I/O polling), check (
setImmediate
) and close callbacks.
3. What are global objects in Node.js? Give examples.
- Global objects are available in every module without import.
- Examples:
global
(Node’s global namespace)process
(information about the current process)Buffer
(binary data handling)
4. How do you check Node.js and npm versions?
- Node.js version:
node --version
- npm version:
npm --version
5. How do you execute a simple “Hello World” HTTP server?
- Create a file
server.js
with: javascriptCopyEditconst http = require('http'); http.createServer((req, res) => { res.end('Hello World'); }).listen(3000);
- Run with
node server.js
and visithttp://localhost:3000
.
6. What is the difference between CommonJS and ES modules in Node js?
- CommonJS (default until v13): uses
require
andmodule.exports
. - ES modules: use
import
andexport
; enable by setting"type": "module"
inpackage.json
or using.mjs
extension.
7. How do you export and import modules using require
and import
?
- CommonJS:
// export module.exports = myFunction; // import const myFunction = require('./myModule');
- ES modules:
// export export function myFunction() { … } // import import { myFunction } from './myModule.js';
8. How does npm work and what is package.json
?
- npm manages packages by downloading from the registry into
node_modules
. package.json
records project metadata, dependencies, scripts and versioning rules.
9. How do you install, update and remove packages globally and locally?
- Local install:
npm install express
- Global install:
npm install –g nodemon
- Update:
npm update <package>
or globallynpm update –g <package>
- Uninstall:
npm uninstall <package>
ornpm uninstall –g <package>
10. What are semantic versioning rules in package.json
?
- Versions follow
MAJOR.MINOR.PATCH
.- MAJOR breaks compatibility,
- MINOR adds features without breaking,
- PATCH fixes bugs.
- Prefixes (
^
and~
) control update ranges:^1.2.3
allows minor and patch updates,~1.2.3
allows patch updates only.
Asynchronous Patterns & Streams Questions | Node JS Developer
11. Explain callbacks and callback hell. How do you avoid it?
- A callback is a function passed into another function to run later.
- Callback hell occurs when callbacks are nested deeply, making code hard to read and maintain.
- Avoid it by using Promises, organizing code into named functions, or leveraging
async
/await
.
12. What are Promises and how do you use them?
- A Promise represents the eventual result of an asynchronous operation.
- It has three states: pending, fulfilled or rejected.
- Use with
.then()
for success and.catch()
for errors: javascriptCopyEditdoAsync() .then(result => { … }) .catch(err => { … });
13. Describe async
/await
and how it simplifies promise handling.
- The
async
keyword marks a function that returns a Promise. await
pauses execution until a Promise resolves or rejects.- Code reads sequentially, reducing nesting:
async function run() { try { const data = await fetchData(); console.log(data); } catch (err) { console.error(err); } }
14. What is the difference between process.nextTick
and setImmediate
?
process.nextTick
queues the callback to run before the next event‑loop tick.setImmediate
queues the callback to run on the next event‑loop iteration, after I/O events.
15. How do you handle uncaught promise rejections?
- Listen for the global event:
process.on('unhandledRejection', err => { console.error('Unhandled rejection:', err); process.exit(1); });
- Always attach
.catch()
to Promises or usetry/catch
withawait
.
16. How do you read and write files synchronously and asynchronously?
- Asynchronous (non‑blocking):
fs.readFile('file.txt', 'utf8', (err, data) => { … }); fs.writeFile('file.txt', data, err => { … });
- Synchronous (blocking):
const data = fs.readFileSync('file.txt', 'utf8'); fs.writeFileSync('file.txt', data);
17. Explain readable and writable streams in Node.js.
- Readable streams emit chunks of data (e.g., file reads).
- Writable streams accept chunks for output (e.g., file writes).
- They allow processing large data without loading it all into memory.
18. How do you pipe streams and why is it useful?
- Use
.pipe()
to connect a readable stream to a writable stream:fs.createReadStream('in.txt').pipe(fs.createWriteStream('out.txt'));
- Useful for efficient data transfer, automatic back‑pressure management and cleaner code.
19. What are Transform streams and when would you use them?
- A Transform stream is both readable and writable: it modifies data as it passes through (e.g., compression, encryption).
- Implement by extending
stream.Transform
or using built‑in transforms likezlib
.
20. How do you manage large file uploads or downloads efficiently?
- Use streams to process data in chunks rather than buffering entire files.
- Combine with middleware (e.g.,
multer
for uploads) and back‑pressure aware piping. - Stream directly to storage services when possible to minimise memory usage.
HTTP, REST, Frameworks & Debugging Questions | Node JS Developer
21. How do you create an HTTP server without frameworks?
- Use the built‑in
http
module:const http = require('http'); http.createServer((req, res) => res.end('OK')).listen(3000);
22. What is Express.js and how do you set up a basic route?
- Express is a minimal web framework for Node.js.
- Basic route:
const app = require('express')(); app.get('/', (req, res) => res.send('Hello')); app.listen(3000);
23. How do you handle middleware in Express?
- Middleware functions process requests before routes.
- Example: javascriptCopyEdit
app.use(express.json()); app.use((req, res, next) => { console.log(req.path); next(); });
24. Explain RESTful API design principles in a Node.js context.
- Use HTTP methods (GET, POST, PUT, DELETE) for actions.
- Resource‑oriented URLs (e.g.,
/users/:id
). - Stateless interactions, proper status codes, and JSON payloads.
25. How do you implement CORS and handle security headers?
- CORS: use the
cors
middleware:const cors = require('cors'); app.use(cors({ origin: 'https://example.com' }));
- Security headers: use
helmet
: javascriptCopyEditconst helmet = require('helmet'); app.use(helmet());
26. How do you handle errors in async callbacks and promises?
- Callbacks: check and return on
err
argument. - Promises: attach
.catch()
or usetry/catch
insideasync
functions.
27. What is the purpose of domain
and why is it deprecated?
domain
provided disposable contexts for error handling across async calls.- It was deprecated due to unpredictable behavior and replaced by
async_hooks
and structured error workflows.
28. How do you use the built‑in debugger or node inspect
?
- Start with
node inspect script.js
. - Use commands like
n
(next),c
(continue) andrepl
to evaluate expressions at breakpoints.
29. How do you log errors and requests in production?
- Use logging libraries like
winston
orpino
. - Log to files or external services, include timestamps and request IDs.
30. How do you perform memory leak detection in a Node.js application?
- Use the
--inspect
flag and Chrome DevTools to take heap snapshots. - Analyze retained objects and growth over time.
- Consider tools like
clinic.js
ormemwatch-next
.
Testing, Performance & Scalability Questions | Node JS Developer
31. What testing frameworks are popular for Node.js?
- Mocha, Jest, Jasmine, and AVA are widely used for unit and integration tests.
32. How do you write unit tests with Mocha or Jest?
- Mocha example:
const assert = require('assert'); describe('sum', () => { it('adds two numbers', () => { assert.strictEqual(sum(1, 2), 3); }); });
- Jest example:
test('adds two numbers', () => { expect(sum(1, 2)).toBe(3); });
33. How do you mock modules or functions in tests?
- Jest: use
jest.mock('moduleName')
orjest.spyOn(obj, 'method')
. - Sinon (with Mocha): use
sinon.stub()
orsinon.mock()
.
34. What is code coverage and how do you measure it?
- Coverage shows which lines are executed by tests.
- Tools like nyc (Istanbul) or built‑in Jest coverage:
nyc mocha # or jest --coverage
35. How do you perform end‑to‑end testing on a Node.js API?
- Use frameworks like SuperTest (for HTTP) or Cypress/Playwright for full-stack flows.
- Example with SuperTest:
const request = require('supertest'); request(app).get('/users').expect(200, done);
36. How do you profile CPU and memory usage in Node.js?
- Run with
--inspect
or--inspect-brk
and use Chrome DevTools’ profiler. - Use clinic.js or 0x for easier CLI-based profiling.
37. What is clustering and how do you implement it?
- Clustering forks multiple worker processes to utilise all CPU cores.
- Example:
const cluster = require('cluster'); if (cluster.isMaster) { for (let i = 0; i < require('os').cpus().length; i++) { cluster.fork(); } } else { require('./server'); }
38. How do you cache data effectively in a Node.js application?
- Use in‑memory stores (e.g., lru-cache) or external caches like Redis/Memcached.
- Cache responses, database queries or computed results with TTLs and eviction policies.
39. Explain load balancing strategies for Node.js servers.
- Round‑robin at the proxy level (Nginx, HAProxy).
- Sticky sessions for stateful apps.
- DNS load balancing or cloud‑provider LBs for global distribution.
40. How do you optimize startup time and reduce latency?
- Minimise module imports, lazy‑load heavy dependencies.
- Pre‑compile or bundle code.
- Use Ahead‑of‑Time compilation tools like ncc or pkg to reduce cold‑start overhead.
Security Best Practices & Advanced Questions | Node JS Developer
41. How do you prevent SQL injection or NoSQL injection attacks?
- Use parameterised queries or prepared statements rather than string concatenation.
- For MongoDB, validate and sanitize inputs, and avoid constructing queries with untrusted data.
42. How do you secure environment variables and secrets?
- Store secrets in environment variables or dedicated secret‑management services (e.g., AWS Secrets Manager).
- Never commit
.env
files to version control; add them to.gitignore
.
43. What is Helmet middleware and how does it help?
helmet
sets HTTP headers to protect against common web vulnerabilities (e.g.,X-Frame-Options
,Strict-Transport-Security
).- Simply add
app.use(require('helmet')())
to enable sensible defaults.
44. How do you implement rate limiting to prevent abuse?
- Use middleware like
express-rate-limit
to cap requests per IP/time window. - Configure sensible limits (e.g., 100 requests per 15 minutes) and use express middleware with Redis or in‑memory stores.
45. How do you protect against cross‑site scripting (XSS) in server responses?
- Escape or sanitize user‑provided data before rendering in HTML.
- Use templating engines with automatic escaping (e.g., Pug, EJS) and set appropriate content‑security policies via headers.
46. What is gRPC and how do you use it with Node.js?
- gRPC is a high‑performance RPC framework using Protocol Buffers.
- In Node.js, install
@grpc/grpc-js
and@grpc/proto-loader
, define.proto
files, load them and create client/server stubs.
47. How do you work with worker threads for CPU‑bound tasks?
- Use the
worker_threads
module to offload CPU‑intensive work to separate threads without blocking the event loop. - Create a
Worker
with a script and communicate via message passing.
48. What are native addons and when would you use them?
- Native addons are C/C++ modules compiled into Node.js to extend functionality or improve performance.
- Use when you need low‑level system access or high‑performance operations not feasible in pure JavaScript.
49. How do you deploy a Node.js application using Docker?
- Write a
Dockerfile
starting from an official Node image, copy source, install dependencies and defineCMD
. - Build:
docker build -t myapp .
- Run:
docker run -d -p 3000:3000 myapp
50. What is the Node.js EventEmitter, and how do you extend it?
EventEmitter
allows objects to emit and listen for named events.- Extend by subclassing: javascriptCopyEdit
const { EventEmitter } = require('events'); class MyEmitter extends EventEmitter {}
- Use
emitter.on('event', handler)
andemitter.emit('event', data)
.
Expert Corner
Node.js’s versatility and performance make it a critical skill for modern backend and full‑stack roles. By working through these fifty questions—covering core concepts, asynchronous patterns, API design, testing, performance tuning and security—you will deepen your practical understanding and build the confidence needed to excel in technical interviews. Remember to implement each example in a development environment, consult the official Node.js documentation for further reading, and continue practising beyond this guide.