Top 25 Nodejs Interview Questions for freshers

Top 25 Node js Interview Questions for freshers

Node.js has become one of the most in-demand skills in today’s backend and full-stack development roles. As more companies move towards scalable, real-time, and high-performance applications, Node.js continues to dominate the hiring scene. Whether you’re preparing for a product-based company or a startup, interviewers often assess your core knowledge, problem-solving skills, and ability to handle asynchronous operations.

This guide gives you the top 25 Node.js interview questions, along with descriptive answers and sample code. We’ve broken them down by topic to help you stay focused and organized during your preparation.

Let’s start with the basics and build up from there.

1. What is Node.js? How is it different from JavaScript in the browser?

Answer:
Node.js is a runtime environment that allows JavaScript to run on the server-side. It uses Chrome’s V8 engine but provides features like file system access, network modules, and process management which the browser doesn’t allow.
Code Example:
javascript
CopyEdit
// Running a basic server using Node.js
const http = require(‘http’);
http.createServer((req, res) => {
  res.write(‘Hello from Node.js!’);
  res.end();
}).listen(3000);
This code won’t run in a browser. But in Node.js, it creates a local server on port 3000.

2. Is Node.js single-threaded or multi-threaded?

Answer:
Node.js operates on a single-threaded event loop, which makes it non-blocking and scalable. Internally, it can use multiple threads (via the libuv library), but the user-facing API is single-threaded.

3. What is the Event Loop in Node.js?

Answer:
The Event Loop is the heart of Node.js. It handles all asynchronous operations in the background and brings the callback functions to the main thread when they’re ready.
Key Stages:
Timers
Pending callbacks
Idle, prepare
Poll
Check
Close callbacks

4. Explain blocking vs non-blocking code in Node.js.

Answer:
Blocking: Halts execution until the task completes.
Non-blocking: Allows execution to continue and uses a callback once the task is done.

Code Example:
javascript
CopyEdit
// Blocking
const fs = require(‘fs’);
const data = fs.readFileSync(‘file.txt’); // blocks here
console.log(data.toString());
 
// Non-blocking
fs.readFile(‘file.txt’, (err, data) => {
  if (err) throw err;
  console.log(data.toString());
});

5. What is npm?

Answer:
npm (Node Package Manager)
is the default package manager for Node.js. It helps install, manage, and version dependencies.
 

6. What is the difference between require() and import?

Answer:
require() is used in CommonJS modules.

import is used in ES6 modules.
 Node.js supports both, but import requires enabling ES modules in package.json.

Example:
javascript
CopyEdit
// CommonJS
const fs = require(‘fs’);
 
// ES6
import fs from ‘fs’;

7. What is middleware in Node.js?

Answer:
 Middleware functions in Node.js (especially in Express.js) are functions that have access to the request, response, and next middleware.
Example:
javascript
CopyEdit
app.use((req, res, next) => {
  console.log(‘Middleware triggered’);
  next();
});

Node.js interview questions github

GitHub is a goldmine for Node.js interview prep. Many recruiters and companies pull questions from open-source repositories or practical project examples available on GitHub. Reviewing Node.js question banks on GitHub helps in understanding the kind of logic or structure real-world applications use.

What to Look For:

  • Real-world projects (Express.js apps, chat servers)
  • GitHub discussions on async issues
  • Repositories like nodejs/node for community Q&A
  • Repo examples with unit tests and production config
8. How do you handle exceptions in Node.js?

Answer:
Node.js offers multiple ways to handle errors:
Try-catch block – for synchronous code
Error-first callbacks – pass the error as the first argument
Promise .catch() and async/await try-catch

Code Example:
javascript
CopyEdit
// Async/Await Error Handling
async function fetchData() {
  try {
    let res = await fetch(‘https://api.example.com/data’);
    let data = await res.json();
    console.log(data);
  } catch (err) {
    console.error(‘Error:’, err);
  }
}

9. What are streams in Node.js?

Answer:
Streams are used to handle reading/writing files, network communication, etc., efficiently. There are four types:
Readable
Writable
Duplex
Transform

Code Example:
javascript
CopyEdit
const fs = require(‘fs’);
const readStream = fs.createReadStream(‘file.txt’);
readStream.on(‘data’, chunk => {
  console.log(chunk.toString());
});

10. How does Node.js handle child processes?

Answer:
 Node.js can spawn child processes using the child_process module. It helps with executing shell commands or running multiple operations in parallel.
Example:
javascript
CopyEdit
const { exec } = require(‘child_process’);
exec(‘ls -la’, (err, stdout, stderr) => {
  if (err) throw err;
  console.log(stdout);
});

Node.js interview technical questions and answers

In technical interviews, candidates are expected to explain logic clearly and back it up with working code examples. These next questions focus on architecture, API handling, and performance, which are common in mid-level to senior Node.js interviews.

11. What is a callback in Node.js? How does it work?

Answer:
A callback is a function passed into another function as an argument. It is called once the outer function completes its task. It’s widely used in asynchronous programming.
Example:
javascript
CopyEdit
function greet(name, callback) {
  console.log(“Hi ” + name);
  callback();
}
greet(‘Shubham’, function () {
  console.log(‘Callback executed!’);
});

12. What are Promises in Node.js?

Answer:
A Promise represents the result of an asynchronous operation. It can be in one of three states:
Pending
Resolved (fulfilled)
Rejected

Code Example:
javascript
CopyEdit
const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(‘Data fetched!’);
    }, 1000);
  });
};
fetchData().then(console.log);

13. Explain async/await in Node.js.

Answer:
async/await makes asynchronous code look synchronous. It’s built on top of Promises and is easier to read.

Example:
javascript
CopyEdit
async function loadData() {
  const data = await fetchData();
  console.log(data);
}
loadData();

14. What is the role of package.json?

Answer:
package.json is the heart of any Node.js project. It holds metadata, dependencies, scripts, and versioning information.

Key fields:
“name”: Project name
“version”: Project version
“dependencies”: Runtime dependencies
“scripts”: Custom commands like npm run start

15. What is Express.js? Why is it used with Node.js?

Answer:
Express.js
is a fast, unopinionated web framework for Node.js. It simplifies routing, middleware management, and server creation.

Code Example:
javascript
CopyEdit
const express = require(‘express’);
const app = express();
 
app.get(‘/’, (req, res) => {
  res.send(‘Hello from Express!’);
});
 
app.listen(3000);

16. How do you handle file uploads in Node.js?

Answer:
Use middleware like Multer with Express to handle multipart/form-data.

Example:
javascript
CopyEdit
const multer = require(‘multer’);
const upload = multer({ dest: ‘uploads/’ });
 
app.post(‘/upload’, upload.single(‘file’), (req, res) => {
  res.send(‘File uploaded!’);
});

17. What is the role of the Buffer class in Node.js?

Answer:
Buffers are used to handle binary data in streams. Unlike strings, buffers work directly with raw memory.

Code Example:
javascript
CopyEdit
const buf = Buffer.from(‘Hello’);
console.log(buf.toString()); // Output: Hello

18. How do you debug Node.js applications?

Answer:
You can use:
console.log() for simple debugging

node –inspect to launch the Chrome DevTools debugger

VSCode’s built-in debugger for breakpoints

19. What are environment variables in Node.js?

Answer:
Environment variables store config outside of your source code. They’re accessed using process.env.

Example:
javascript
CopyEdit
console.log(process.env.PORT); // Prints the PORT value
 
Use .env files with libraries like dotenv for cleaner config.

20. How do you manage memory in Node.js?

Answer:
Node.js uses automatic garbage collection, but memory leaks can still happen. Use:
–inspect for heap snapshots

Tools like memwatch-next, heapdump, or Chrome DevTools

This section expands into performance optimization, security, and scalability, which are critical in system design interviews or when you’re asked to review a Node.js app during your hiring process.

21. How do you prevent callback hell?

Answer:
You can prevent callback hell using:
Modular functions
Promises
async/await

Before:
javascript
CopyEdit
getUser(id, function(user) {
  getOrders(user, function(orders) {
    getItems(orders, function(items) {
      console.log(items);
    });
  });
});
 
After:
javascript
CopyEdit
async function loadItems(id) {
  const user = await getUser(id);
  const orders = await getOrders(user);
  const items = await getItems(orders);
  console.log(items);
}

22. What are some common security practices in Node.js?

Answer:
Use helmet to secure HTTP headers
Sanitize inputs to avoid injection attacks
Use HTTPS for communication
Never store credentials in code
Use rate-limiting and JWT for auth

23. What is CORS and how do you handle it in Node.js?

Answer:
CORS (Cross-Origin Resource Sharing)
is a security feature that blocks calls from different domains unless explicitly allowed

Code Example:
javascript
CopyEdit
const cors = require(‘cors’);
app.use(cors());

24. What is clustering in Node.js?

Answer:
Clustering allows you to take advantage of multi-core systems by running multiple instances of your app.

Code Example:
javascript
CopyEdit
const cluster = require(‘cluster’);
const http = require(‘http’);
const numCPUs = require(‘os’).cpus().length;
 
if (cluster.isMaster) {
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  http.createServer((req, res) => {
    res.end(‘Handled by worker’);
  }).listen(8000);
}

Freshers often worry about interviews because they feel they lack real-world experience. But interviewers don’t expect production-grade answers—they want clarity, logic, and understanding. These questions below are tailored for freshers and early-career developers applying for backend or full-stack roles.

25. What are the core modules in Node.js?

Answer:
Node.js also has in-built modules. There is no need to install them. Such tasks include file operations, networking, cryptography and data streaming are being done by them

Common core modules:
fs – file system
http – web server
path – file paths
os – operating system info
events – event handling

Example:
javascript
CopyEdit
const os = require(‘os’);
console.log(‘CPU Cores:’, os.cpus().length);

Bonus: What is the difference between setTimeout and setImmediate in Node.js?

Answer:
setTimeout(fn, 0) runs after a minimum delay of 0ms.
setImmediate(fn) runs immediately after I/O events.

They may seem the same, but they execute at different phases of the event loop.

What is the use of process.nextTick()?

Answer:
process.nextTick() schedules a callback to run before the event loop continues. It’s useful for deferring execution of code after the current operation completes but before I/O.

Example:
javascript
CopyEdit
console.log(‘Start’);
 
process.nextTick(() => {
  console.log(‘Next Tick’);
});
 
console.log(‘End’);
 
// Output:
// Start
// End
// Next Tick
 

Explain the concept of a server in Node.js.

Answer:
A server listens for incoming HTTP requests and sends back responses. Node.js can easily set up lightweight servers without any external web server like Apache or Nginx.

Example:
javascript
CopyEdit
const http = require(‘http’);
 
const server = http.createServer((req, res) => {
  res.writeHead(200, {‘Content-Type’: ‘text/plain’});
  res.end(‘Node.js server is running!’);
});
 
server.listen(3000, () => {
  console.log(‘Server is listening on port 3000’);
});

What is the role of the eventEmitter in Node.js?

Answer:
The EventEmitter class lets you create and handle custom events in Node.js.

Example:
javascript
CopyEdit
const EventEmitter = require(‘events’);
const emitter = new EventEmitter();
 
emitter.on(‘greet’, () => {
  console.log(‘Hello from EventEmitter!’);
});
 
emitter.emit(‘greet’);

How can a fresher show Node.js skills during interviews?

Tips:
Build and explain a basic CRUD app using Express and MongoDB
Share a GitHub repo with clean folder structure
Mention use of Postman for testing APIs
Talk about middleware, routing, error handling, and async logic
Prepare a short demo of login/signup or file upload

Summary Table: Quick Look at Core Concepts

ConceptDescriptionExample / Use Case
CallbackAsync function within a functionReading a file asynchronously
PromiseHandle async success/failureAPI calls using .then() or .catch()
async/awaitSyntactic sugar over PromisesCleaner async code
MiddlewareLogic before reaching routeAuth check, body parsing
BufferBinary data handlingStreaming file content
ClusterMulti-core load handlingHigh traffic Node.js servers
EventEmitterCustom event managementReusable architecture

When and How to Use Node.js in Real Projects

Node.js is perfect for:

  • Real-time apps like chats, games, notifications
  • APIs for mobile or SPA frontends
  • Microservices architecture
  • Data streaming (e.g., processing logs, files, audio)
  • Server-side rendering (SSR) using tools like Next.js

But avoid using Node.js for CPU-heavy operations like video encoding or scientific simulations, as it’s single-threaded by design.

Mastering Node.js demands structured learning, expert guidance, and hands-on practice. That’s where ESS Institute steps in. We have helped hundreds of learners transform into industry-ready backend developers. You could be next by joining our best Mern stack development course in Delhi and online mern stack course in Hindi

Call Now