Node.js Basic Interview Q&A

Are you preparing for a Node.js interview? Whether you are a beginner or looking to refresh your knowledge, this page covers fundamental Node.js questions that are commonly asked in interviews.

What is Node.js?

Node.js is an open-source, cross-platform runtime environment that allows JavaScript to run on the server side. It is built on Chrome’s V8 JavaScript engine and uses an event-driven, non-blocking I/O model for high-performance applications.

What are the key features of Node.js?

  • Asynchronous and Event-Driven: Uses callbacks to handle tasks asynchronously.
  • Single-Threaded but Scalable: Uses the event loop mechanism instead of traditional multi-threading.
  • Non-Blocking I/O: Operations are handled asynchronously, improving performance.
  • Built on V8 Engine: Ensures fast execution of JavaScript code.
  • NPM (Node Package Manager): Provides access to thousands of libraries.
  • Fast Execution: Built on the V8 engine, making it efficient.
  • Scalability: Handles a large number of concurrent connections.
  • Cross-Platform: Runs on Windows, Linux, and macOS.

What is the difference between Node.js and JavaScript?

FeatureJavaScriptNode.js
ExecutionRuns in browsersRuns outside browsers (Server)
PurposeClient-side scriptingServer-side scripting
ModulesUses ES6 modulesUses CommonJS modules (require)
APIsDOM manipulationFile system, network, database, etc.

What is npm?

npm (Node Package Manager) is the default package manager for Node.js. It is used to install, update, and manage JavaScript packages and dependencies.

Commands:

  • npm init → Initialize a new project.
  • npm install <package> → Install a package.
  • npm list → List installed packages.
  • npm update <package> → Update a package.

What is the difference between dependencies and devDependencies in package.json?

  • dependencies → Required for production ("dependencies": { "express": "^4.0.0" }).
  • devDependencies → Required only for development ("devDependencies": { "nodemon": "^2.0.0" }).

Install with:

  • npm install <package> --save (for dependencies)
  • npm install <package> --save-dev (for devDependencies)

What is the purpose of the event loop in Node.js?

The event loop is a mechanism in Node.js that allows it to handle multiple requests asynchronously in a single-threaded environment. It continuously checks the call stack and callback queue to execute tasks efficiently.

What are callbacks in Node.js?

A callback is a function passed as an argument to another function and executed after the completion of an asynchronous task.

Example:

javascriptCopyEditconst fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
});

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

  • Synchronous (Blocking) → Executes code line by line, waiting for one task to complete before moving to the next.
  • Asynchronous (Non-blocking) → Does not wait for a task to complete before moving to the next one, improving performance.

Example:

// Synchronous (Blocking)
const data = fs.readFileSync('file.txt', 'utf8');
console.log(data);

// Asynchronous (Non-blocking)
fs.readFile('file.txt', 'utf8', (err, data) => {
    console.log(data);
});

What is middleware in Express.js?

Middleware functions in Express.js are functions that have access to the request (req), response (res), and the next function in the application’s request-response cycle.

Example of Middleware:

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

// Middleware function
app.use((req, res, next) => {
    console.log('Middleware executed');
    next();
});

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

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

What is the difference between CommonJS and ES6 modules in Node.js?

FeatureCommonJSES6 Modules
Syntaxrequire()import
Exportmodule.exportsexport
ScopeModules are loaded synchronouslyModules are loaded asynchronously
SupportDefault in Node.jsNeeds "type": "module" in package.json

Example:

// CommonJS
const fs = require('fs');

// ES6 Modules
import fs from 'fs';

How does Node.js handle file operations?

Node.js provides the fs (File System) module to handle file operations.

Reading a File:

const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
});

Writing to a File:

fs.writeFile('file.txt', 'Hello Node.js', (err) => {
    if (err) throw err;
    console.log('File written successfully');
});

What is the difference between process.nextTick() and setImmediate()?

  • process.nextTick() executes callbacks before the event loop continues.
  • setImmediate() executes callbacks after the event loop completes the current cycle.

Example:

console.log("Start");

setImmediate(() => console.log("setImmediate"));
process.nextTick(() => console.log("nextTick"));

console.log("End");

Output:

Start
End
nextTick
setImmediate

What is the purpose of the cluster module in Node.js?

The cluster module allows Node.js to create multiple processes, utilizing multi-core systems for better performance.

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

if (cluster.isMaster) {
    for (let i = 0; i < os.cpus().length; i++) {
        cluster.fork();
    }
} else {
    http.createServer((req, res) => {
        res.writeHead(200);
        res.end('Hello, World!');
    }).listen(8000);
}

What is the difference between fork() and spawn() in Node.js?

MethodDescription
spawn()Creates a new process with a separate memory space (used for streaming data).
fork()Creates a new process that shares memory with the parent process (used for IPC – Inter Process Communication).

How to handle errors in Node.js?

Error handling can be done using:

  • Try-Catch (for synchronous code)
  • Callbacks (for asynchronous code)
  • Promises & Async/Await

Leave a Reply

Your email address will not be published. Required fields are marked *