Node.js Interview Questions

Browse through our curated collection of questions

What is CORS and how do you handle it?
Medium
Answer:

CORS (Cross-Origin Resource Sharing) is like a security guard that controls which websites can access your API. By default, browsers block requests from different domains.

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

// Enable CORS for all routes
app.use(cors());

// Or configure specific origins
app.use(cors({
  origin: ['http://localhost:3000', 'https://mywebsite.com'],
  methods: ['GET', 'POST'],
  credentials: true
}));

app.get('/api/data', (req, res) => {
  res.json({ message: 'This API can be accessed from allowed origins' });
});
How do you handle errors in Node.js?
Medium
Answer:

Error handling is like having a safety net. You catch errors before they crash your application.

// Try-catch for synchronous code
try {
  const data = JSON.parse('invalid json');
} catch (error) {
  console.log('Error parsing JSON:', error.message);
}

// Error handling in async/await
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.log('Error fetching data:', error.message);
    throw error;
  }
}

// Global error handler
process.on('uncaughtException', (error) => {
  console.log('Uncaught Exception:', error);
  process.exit(1);
});
What is the difference between process.nextTick() and setImmediate()?
Medium
Answer:

Both schedule functions to run later, but at different times:

  • process.nextTick(): Runs before any other asynchronous operation
  • setImmediate(): Runs after I/O events
console.log('Start');

setImmediate(() => {
  console.log('setImmediate');
});

process.nextTick(() => {
  console.log('nextTick');
});

console.log('End');

// Output:
// Start
// End
// nextTick
// setImmediate
What is Clustering in Node.js?
Medium
Answer:

Clustering is like having multiple workers doing the same job. If one worker gets busy, others can handle new requests.

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Create worker processes
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  // Worker process
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello from worker process');
  }).listen(3000);
}
What are Streams in Node.js?
Medium
Answer:

Streams are like water flowing through a pipe. Instead of loading entire large files into memory, streams process data piece by piece.

const fs = require('fs');

// Reading large file using streams
const readStream = fs.createReadStream('large-file.txt');
const writeStream = fs.createWriteStream('copy-file.txt');

readStream.pipe(writeStream);

readStream.on('data', (chunk) => {
  console.log('Received chunk of data');
});
What is Buffer in Node.js?
Medium
Answer:

Buffer is used to handle binary data (like images, videos, or files). Think of it as a temporary storage area for raw data.

// Create a buffer
const buf = Buffer.from('Hello World', 'utf8');
console.log(buf); // <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>

// Convert back to string
console.log(buf.toString()); // Hello World
What is the difference between dependencies and devDependencies?
Easy
Answer:
  • dependencies: Packages your app needs to run (like Express for a web server)
  • devDependencies: Packages you only need during development (like testing tools)

Real-life example: Dependencies are like the engine in your car (needed to drive), devDependencies are like the tools in your garage (only needed for maintenance).

{
  "dependencies": {
    "express": "^4.18.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.15",
    "jest": "^27.5.0"
  }
}
What is package.json?
Easy
Answer:

package.json is like an ID card for your Node.js project. It contains information about your project and lists all the external packages your project needs.

{
  "name": "my-awesome-app",
  "version": "1.0.0",
  "description": "My first Node.js app",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
  },
  "dependencies": {
    "express": "^4.18.0"
  }
}
What is the difference between require() and import?
Easy
Answer:
  • require() is the old way (CommonJS)
  • import is the new way (ES6 modules)
// Using require() - CommonJS
const express = require('express');
const { add } = require('./math');

// Using import - ES6 modules
import express from 'express';
import { add } from './math.js';
What is Middleware?
Medium
Answer:

Middleware is like security checkpoints at an airport. Every request passes through these checkpoints before reaching its final destination.

// Logging middleware
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url} - ${new Date()}`);
  next(); // Pass control to next middleware
});

// Authentication middleware
app.use('/admin', (req, res, next) => {
  if (req.headers.authorization) {
    next(); // User is authorized
  } else {
    res.status(401).send('Please login first');
  }
});