The Node js interview questions freshers face most often cover the event loop, asynchronous code, modules, npm, Express and error handling, and this guide answers 30 of them with short explanations and code. Node.js is a JavaScript runtime built on Chrome’s V8 engine that lets you run JavaScript on the server. Companies hiring for full stack and backend roles in India use Node.js widely, so interviewers expect you to explain how it works, not only how to write a route. Read each answer, then type and run the code yourself.
Key takeaways
- Node.js runs JavaScript on a single main thread and handles concurrency through a non-blocking event loop.
- Expect questions on callbacks, Promises and async/await, and be ready to rewrite callback code using async/await.
- Know the difference between CommonJS require and ES module import, and how package.json controls which one is used.
- Express middleware, error handling and environment variables come up in almost every practical round.
- Practise by building a small REST API with Express and a database, since many interviews include a live coding task.
Basic Node js interview questions
1. What is Node.js?
Node.js is an open-source, cross-platform runtime that executes JavaScript outside the browser. It uses the V8 engine for JavaScript and the libuv library for asynchronous input and output, which makes it good for network servers and APIs.
2. Is Node.js a framework or a language?
Neither. JavaScript is the language and Node.js is the runtime environment. Express, NestJS and Fastify are frameworks built on top of Node.js.
3. Why is Node.js called single-threaded?
Your JavaScript code runs on one main thread. Slow tasks such as file reads, network calls and some crypto work are handed to the operating system or to libuv’s thread pool, and their results come back to the main thread as callbacks. So the code you write is single-threaded, but Node.js itself uses extra threads behind the scenes.
4. What is the event loop?
The event loop is the mechanism that keeps checking for completed work and runs the matching callbacks. It moves through phases such as timers, pending callbacks, poll, check and close callbacks. Because it never waits idly for input or output, one Node.js process can serve many connections at once.
5. What does non-blocking I/O mean?
Non-blocking means Node.js starts an input or output task and moves on immediately instead of waiting. When the task finishes, a callback or Promise delivers the result.
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, text) => {
if (err) return console.error(err);
console.log(text);
});
console.log('This prints first');
6. What is npm?
npm is the default package manager for Node.js. It installs libraries from the npm registry, records them in package.json and locks exact versions in package-lock.json.
7. What is the difference between dependencies and devDependencies?
dependencies are needed when the app runs in production, such as Express. devDependencies are only needed while developing or testing, such as Jest or ESLint. Install a dev dependency with npm install –save-dev.
8. What is package.json?
package.json describes your project: its name, version, scripts, dependencies and settings such as the module type. Running npm init creates it.
9. What are modules in Node.js?
A module is a file whose variables and functions are private unless you export them. Node.js has built-in modules such as fs, path and http, third-party modules from npm, and your own local modules.
10. What is the difference between require and import?
require belongs to CommonJS, the original Node.js module system, and loads modules synchronously. import belongs to ES modules, the JavaScript standard. Node.js treats a file as an ES module if it ends in .mjs or if package.json contains a type field set to module.
// CommonJS
const path = require('path');
module.exports = { add };
// ES module
import path from 'path';
export function add(a, b) { return a + b; }
Asynchronous programming questions
11. What is a callback?
A callback is a function passed to another function to be run later, usually when an asynchronous task finishes. Node.js core APIs traditionally use error-first callbacks, where the first argument is an error or null.
12. What is callback hell and how do you avoid it?
Callback hell is deeply nested callbacks that are hard to read and debug. You avoid it by using Promises, async/await, small named functions and proper error handling.
13. What is a Promise?
A Promise represents a value that will be available later. It is pending at first, then either fulfilled with a value or rejected with an error. You handle it with then and catch, or with await.
14. How does async/await work?
An async function always returns a Promise. Inside it, await pauses that function until the Promise settles, without blocking the event loop. Wrap awaits in try and catch to handle errors.
const fs = require('fs/promises');
async function readConfig() {
try {
const text = await fs.readFile('config.json', 'utf8');
return JSON.parse(text);
} catch (err) {
console.error('Could not read config', err.message);
return {};
}
}
15. What is the difference between Promise.all and Promise.allSettled?
Promise.all waits for every Promise and rejects as soon as any one fails. Promise.allSettled waits for all of them and gives you each result with a status of fulfilled or rejected, so one failure does not hide the others.
16. What is the difference between process.nextTick and setImmediate?
process.nextTick runs its callback right after the current operation, before the event loop continues. setImmediate runs its callback in the check phase of the next loop iteration. Overusing nextTick can starve the event loop.
17. What are microtasks and macrotasks?
Microtasks include Promise callbacks and queueMicrotask, and they run as soon as the current task finishes. Macrotasks include setTimeout, setInterval, setImmediate and I/O callbacks. All pending microtasks run before the next macrotask.
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('sync');
// Output: sync, promise, timeout
Core modules and runtime questions
18. What is the EventEmitter?
EventEmitter, from the events module, lets objects emit named events and lets listeners react to them. Streams, HTTP servers and many libraries are built on it.
const EventEmitter = require('events');
const bus = new EventEmitter();
bus.on('order', (id) => console.log('New order', id));
bus.emit('order', 101);
19. What are streams?
Streams process data piece by piece instead of loading it all into memory. There are four types: readable, writable, duplex and transform. They are ideal for large files, video and network data.
const fs = require('fs');
fs.createReadStream('big.log').pipe(fs.createWriteStream('copy.log'));
20. What is a Buffer?
A Buffer holds raw binary data in memory. Node.js uses Buffers for file contents, network packets and anything that is not plain text.
21. What is the difference between readFile and readFileSync?
readFile is asynchronous and does not block the event loop. readFileSync blocks until the file is read. Use the sync version only in startup scripts or command-line tools, never inside request handlers.
22. How do you handle CPU-heavy work in Node.js?
CPU-heavy work blocks the main thread, so move it off. Options include the worker_threads module, splitting work into separate services, or running multiple processes with the cluster module or a process manager.
23. What is the cluster module?
The cluster module starts several Node.js processes that share the same server port, so an app can use multiple CPU cores. In production, many teams use a process manager or containers instead.
24. How do you use environment variables?
Read them from process.env. Keep secrets such as database passwords out of your code, load them from the environment or a secrets manager, and use a .env file only for local development.
Express and API questions
25. What is Express.js?
Express is a minimal web framework for Node.js. It adds routing, middleware and helpers for requests and responses, which makes building REST APIs quick.
const express = require('express');
const app = express();
app.use(express.json());
app.get('/api/health', (req, res) => {
res.json({ status: 'ok' });
});
app.listen(3000, () => console.log('Listening on 3000'));
26. What is middleware in Express?
Middleware is a function that receives the request, the response and next. It can read or change them, end the response, or call next to pass control on. Logging, authentication and body parsing are usually middleware.
27. How do you handle errors in Express?
Add an error-handling middleware with four parameters at the end of your middleware chain. In async route handlers, catch errors and pass them to next so they reach it.
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Something went wrong' });
});
28. What is CORS and how do you enable it?
CORS is a browser rule that blocks a page from calling an API on a different origin unless the server allows it. In Express you usually add the cors package and configure the allowed origins rather than allowing everything.
29. How do you secure a Node.js API?
Validate all input, hash passwords with bcrypt or argon2, use HTTPS, set security headers with a package such as helmet, apply rate limiting, keep dependencies updated with npm audit, and never log secrets.
30. How do you connect Node.js to a database?
Use a driver or library for your database: mongoose or the official MongoDB driver for MongoDB, pg for PostgreSQL, or an ORM such as Prisma or Sequelize. Use connection pooling and keep credentials in environment variables.
How to prepare for a Node.js interview
- Revise core JavaScript first: closures, this, prototypes and Promises. Our JavaScript interview questions cover these.
- Build one REST API with Express, a database, validation and error handling, and push it to GitHub.
- Be able to draw the event loop and explain the output of a short async snippet.
- Understand how Node.js fits into the MERN stack with MongoDB, Express and React.
- Review broader questions in our full stack developer interview questions.
Frequently asked questions
Is Node.js good for freshers?
Yes. If you already know JavaScript from front-end work, Node.js lets you use the same language on the server, which makes it one of the easier ways to become a full stack developer.
Which Node.js topics are asked most in interviews?
The event loop, async/await and Promises, modules, Express middleware, error handling and REST API design are asked most often, followed by streams and security basics.
Do I need to learn Express for a Node.js interview?
For most web roles, yes. Express is the most common Node.js framework, and many practical rounds ask you to build or debug a small Express API.
Which Node.js version should I learn?
Learn on the current Long Term Support release. Check the official Node.js website for the active LTS version, since it changes every year.
Explore more full stack guides in our full stack category.
