NodeJs Interview Questions

1. What is Node.js, and why is it used?

Node.js is an open-source, cross-platform JavaScript runtime environment that allows JavaScript to run outside the browser. It is built on Chrome's V8 engine and follows a non-blocking, event-driven architecture, making it ideal for scalable, real-time, and high-performance applications.

Why use Node.js?

  1. Asynchronous & Non-blocking I/O for high performance

  2. Single-threaded but handles multiple requests efficiently

  3. Fast execution due to V8 engine

  4. Ideal for APIs, real-time apps, and microservices

2. What tools can be used to assure consistent code style?

ESLint can be used with any IDE to ensure a consistent coding style which further helps in maintaining the codebase.

3. What is the difference between synchronous and asynchronous programming in Node.js?

Feature Synchronous (Blocking) Asynchronous (Non-Blocking)
Execution Code executes line by line Code does not wait; continues execution
Performance Slower (blocks execution) Faster (non-blocking)
Example fs.readFileSync() fs.readFile() with a callback

Example:

Synchronous (Blocking):

const fs = require('fs');
const data = fs.readFileSync('file.txt', 'utf8');
console.log(data); // Waits for file reading
console.log("This runs after file read");

Asynchronous (Non-Blocking):

fs.readFile('file.txt', 'utf8', (err, data) => {
    console.log(data);  // Runs later
});
console.log("This runs first");

4. How do you manage packages in your node.js project?

It can be managed by a number of package installers and their configuration file accordingly. Out of them mostly use npm or yarn. Both provide almost all libraries of javascript with extended features of controlling environment-specific configurations. To maintain versions of libs being installed in a project we use package.json and package-lock.json so that there is no issue in porting that app to a different environment.

5. What are Streams in Node.js?

Streams are data-handling objects in Node.js that allow reading/writing data efficiently in chunks instead of loading it all at once.

Types of Streams:

  1. Readable Streams → fs.createReadStream() (e.g., reading a file)

  2. Writable Streams → fs.createWriteStream() (e.g., writing to a file)

  3. Duplex Streams → Readable & Writable (e.g., TCP sockets)

  4. Transform Streams → Modify data while reading/writing (e.g., compression)

Example: Read a file using streams:

const fs = require('fs');
const readStream = fs.createReadStream('data.txt', 'utf8');

readStream.on('data', (chunk) => {
    console.log(chunk);  // Reads data in chunks
});

6. Explain callback in Node.js

A callback function is called after a given task. It allows other code to be run in the meantime and prevents any blocking. Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks.

7. What is Middleware in Express.js?

Middleware functions in Express.js are functions that execute during request processing before sending a response.

Types of Middleware:

  1. Application-level middleware : app.use((req, res, next) => {...})

  2. Router-level middleware : router.use(...)

  3. Error-handling middleware : (err, req, res, next) => {...}

  4. Built-in middleware : express.json(), express.static()

Example:

const express = require('express');
const app = express();

// Middleware function
app.use((req, res, next) => {
    console.log('Request received:', req.method, req.url);
    next();  // Pass to next middleware
});

app.get('/', (req, res) => {
    res.send('Hello, Express!');
});

app.listen(3000, () => console.log('Server running on port 3000'));

8. How is Node.js most frequently used?

Node.js is widely used in the following applications:

  1. Real-time chats

  2. Internet of Things

  3. Complex SPAs (Single-Page Applications)

  4. Real-time collaboration tools

  5. Streaming applications

  6. Microservices architecture

9. Explain the difference between frontend and backend development?

Front-end Back-end
Frontend refers to the client-side of an application Backend refers to the server-side of an application
It is the part of a web application that users can see and interact with It constitutes everything that happens behind the scenes
It typically includes everything that attributes to the visual aspects of a web application It generally includes a web server that communicates with a database to serve requests
HTML, CSS, JavaScript, AngularJS, and ReactJS are some of the essentials of frontend development Java, PHP, Python, and Node.js are some of the backend development technologies

10.What is Clustering in Node.js?

Clustering allows Node.js to create multiple processes (workers) on multi-core CPUs, improving performance.

Example using cluster module:

const cluster = require('cluster');
const http = require('http');
const os = require('os');

if (cluster.isMaster) {
    // Fork workers
    os.cpus().forEach(() => cluster.fork());
} else {
    http.createServer((req, res) => {
        res.writeHead(200);
        res.end('Hello from Worker ' + process.pid);
    }).listen(3000);
}

Each worker runs independently but shares the same port.

11. What are the modules in Node.js?

Modules are like JavaScript libraries that can be used in a Node.js application to include a set of functions. To include a module in a Node.js application, use the require() function with the parentheses containing the module's name.

Node.js has many modules to provide the basic functionality needed for a web application. Some of them include:

Core Modules Description
HTTP Includes classes, methods, and events to create a Node.js HTTP server
util Includes utility functions useful for developers
fs Includes events, classes, and methods to deal with file I/O operations
url Includes methods for URL parsing
query string Includes methods to work with query string
stream Includes methods to handle streaming data
zlib Includes methods to compress or decompress files

12. How to handle errors in Node.js?

  1. Try-Catch (for synchronous errors)

  2. Event Listeners (process.on('uncaughtException'))

  3. Promises (.catch())

  4. Async/Await (try...catch)

Example:

try {
    throw new Error("Something went wrong!");
} catch (error) {
    console.error(error.message);
}

13. What is the difference between CommonJS and ES6 Modules?

Feature CommonJS (require()) ES6 Modules (import)
Syntax const module = require('module') import module from 'module'
File Extension .js .mjs (or add "type": "module" in package.json)
Export Method module.exports = {...} export default or export {}
Synchronous/Async Synchronous Asynchronous

Example:

CommonJS:

// module.js
module.exports = { greet: () => console.log('Hello!') };

// main.js
const { greet } = require('./module');
greet();

ES6 Module:

// module.mjs
export const greet = () => console.log('Hello!');

// main.mjs
import { greet } from './module.mjs';
greet();

14. What is an Event Loop in Node.js?

Event loops handle asynchronous callbacks in Node.js. It is the foundation of Node.js's non-blocking input/output in Node.js, making it one of the most important environmental features.

15. What are the two types of API functions in Node.js?

The two types of API functions in Node.js are:

  1. Asynchronous, non-blocking functions

  2. Synchronous, blocking functions

16. What are the different types of HTTP requests?

HTTP defines a set of request methods used to perform desired actions. The request methods include:

  1. GET : Used to retrieve the data

  2. POST : Generally used to make a change in state or reactions on the server

  3. HEAD : Similar to the GET method, but asks for the response without the response body

  4. DELETE : Used to delete the predetermined resource

17. What are global objects in Node.js?

Global objects in Node.js are objects that are available in all modules without the need for an explicit require statement. Some of the most commonly used global objects in Node.js include process, console, and buffer.

18. Explain the concept of middleware in Node.js.

Middleware is a function that receives the request and response objects. Most tasks that the middleware functions perform are:

  1. Execute any code

  2. Update or modify the request and the response objects

  3. Finish the request-response cycle

  4. Invoke the next middleware in the stack

19. What is the difference between setImmediate() and setTimeout()?

The setTimeout() method schedules code execution after a specified delay, measured in milliseconds. On the other hand, the setImmediate() method schedules code execution to occur immediately after the current event loop iteration completes. This means that setImmediate() has a higher priority than setTimeout().

20. What is the difference between readFile and create Read Stream in Node.js?

Create Read Stream is a better option for reading large files, while the read file is a better option for small files. It is important to choose the right method based on the file size and the application's requirements.