Lesson 50 of 50 – Node.js Interview Questions
100% Completed
100%

Node.js Interview Questions and Answers

Revise important Node.js concepts, JavaScript asynchronous programming, Express.js, REST APIs, databases, authentication, and deployment through these interview questions and answers.

Congratulations! You have reached the final lesson of the 50-lesson Node.js tutorial series. Use this lesson to revise important concepts and prepare for technical interviews.

Section 1: Node.js Basics

Q1. What is Node.js?

Node.js is a JavaScript runtime that allows developers to execute JavaScript outside a web browser. It is commonly used to build servers, APIs, command-line tools, and real-time applications.

Q2. Is Node.js a programming language?

No. JavaScript is the programming language, while Node.js is a runtime environment for executing JavaScript outside the browser.

Q3. What is npm?

npm stands for Node Package Manager. It is commonly used to install packages, manage project dependencies, and run scripts.

npm init -y
npm install express
npm uninstall express
Q4. What is package.json?

package.json stores project information, scripts, and dependency declarations for a Node.js project.

{
    "name": "my-project",
    "version": "1.0.0",
    "scripts": {
        "start": "node server.js"
    }
}
Q5. What is the difference between Node.js and a browser?

Both can execute JavaScript, but they provide different runtime APIs. Browsers provide APIs such as the DOM and window, while Node.js provides APIs such as file-system access through node:fs.

Section 2: Modules and Core Modules

Q6. What is a module in Node.js?

A module is a reusable unit of code. Modules help developers organize applications into separate files and components.

Q7. What is CommonJS?

CommonJS is a module system commonly used in Node.js. It uses require() to import modules and module.exports to export values.

// math.js
function add(a, b) {
    return a + b;
}

module.exports = { add };

// app.js
const { add } = require('./math');

console.log(add(10, 20));

Output: 30

Q8. What are ES Modules?

ES Modules are JavaScript's standard module system. They use import and export.

// math.js
export function add(a, b) {
    return a + b;
}

// app.js
import { add } from './math.js';

console.log(add(5, 10));

Configure the project for ES Modules, for example by setting "type": "module" in package.json.

Q9. What is the path module?

The node:path module provides utilities for working with file and directory paths.

const path = require('node:path');

console.log(path.join('public', 'images', 'logo.png'));

Output: public/images/logo.png on POSIX systems.

Q10. What is the File System module?

The node:fs module allows applications to read, write, update, and delete files.

const fs = require('node:fs');

fs.writeFileSync('message.txt', 'Hello Node.js');

const data = fs.readFileSync('message.txt', 'utf8');

console.log(data);

Section 3: Asynchronous Programming

Q11. What is asynchronous programming?

Asynchronous programming allows an application to start an operation and continue other work while waiting for that operation to finish.

It is useful for operations such as file access, database requests, and network communication.

Q12. What is a callback?

A callback is a function passed to another function to be called later or when a particular operation completes.

function greet(name, callback) {
    console.log('Hello ' + name);
    callback();
}

greet('Rahul', function() {
    console.log('Welcome!');
});

Output:

Hello Rahul
Welcome!
Q13. What is callback hell?

Callback hell occurs when callbacks are nested deeply, making code difficult to read and maintain.

Promises and async/await can help structure asynchronous code more clearly.

Q14. What is a Promise?

A Promise represents the eventual success or failure of an asynchronous operation. Its states are pending, fulfilled, and rejected.

const promise = new Promise((resolve, reject) => {
    const success = true;

    if (success) {
        resolve('Operation successful');
    } else {
        reject(new Error('Operation failed'));
    }
});

promise
    .then(result => console.log(result))
    .catch(error => console.error(error.message));
Q15. What is async/await?

async and await provide a readable way to work with Promises. An async function returns a Promise.

async function getData() {
    try {
        const result = await Promise.resolve('Data received');
        console.log(result);
    } catch (error) {
        console.error(error);
    }
}

getData();
Q16. What is the event loop?

The event loop coordinates JavaScript execution with asynchronous callbacks and other runtime work. It helps Node.js handle many I/O operations without blocking the main JavaScript thread while those operations wait.

Section 4: Express.js and REST APIs

Q17. What is Express.js?

Express.js is a web framework for Node.js. It provides routing, middleware support, and tools for handling HTTP requests and responses.

const express = require('express');

const app = express();

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

app.listen(3000);
Q18. What is middleware?

Middleware is a function that can inspect or modify a request, modify a response, end the request-response cycle, or pass control to the next middleware.

app.use((req, res, next) => {
    console.log(req.method, req.url);
    next();
});

Call next() when the middleware should pass control onward. If it neither sends a response nor passes control, the request may remain unfinished.

Q19. What is a REST API?

A REST-style API exposes resources through URLs and uses HTTP methods to perform operations on those resources.

Method Common Purpose
GET Read a resource
POST Create a resource
PUT Replace a resource or its representation
PATCH Partially update a resource
DELETE Delete a resource
Q20. What is the difference between req.params and req.query?

req.params contains named route parameters, while req.query contains query-string parameters.

// Route: /students/10
app.get('/students/:id', (req, res) => {
    res.send(req.params.id);
});

// URL: /students?course=Python
app.get('/students', (req, res) => {
    res.send(req.query.course || 'All courses');
});
Q21. What is CORS?

CORS stands for Cross-Origin Resource Sharing. It is a browser security mechanism controlled by HTTP response headers that determines whether browser code from another origin may access a response.

Configure CORS for the specific frontend origins that should access your API.

Section 5: Databases

Q22. How can Node.js connect to MySQL?

Node.js can connect to MySQL using a driver such as mysql2. Database credentials should be supplied through secure configuration.

const mysql = require('mysql2/promise');

async function main() {
    const connection = await mysql.createConnection({
        host: process.env.DB_HOST,
        user: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME
    });

    try {
        const [rows] = await connection.execute(
            'SELECT id, name FROM students WHERE id = ?',
            [1]
        );

        console.log(rows);
    } finally {
        await connection.end();
    }
}

main().catch(console.error);

Install the driver using npm install mysql2 and configure the required environment variables first.

Q23. What is MongoDB?

MongoDB is a document-oriented database that stores records as BSON documents. Node.js applications can interact with it using the MongoDB driver or Mongoose.

Q24. What is SQL injection?

SQL injection is a security vulnerability in which untrusted input changes the meaning of a SQL query.

Use parameterized queries rather than concatenating user input into SQL strings.

// Safer parameterized query
const [rows] = await connection.execute(
    'SELECT * FROM students WHERE email = ?',
    [email]
);

Section 6: Authentication and Security

Q25. What is authentication?

Authentication verifies a user's identity, for example by checking credentials during login.

Q26. What is authorization?

Authorization determines what an authenticated user is allowed to access or do.

For example, a student may view their own profile, while an authorized administrator may manage student records.

Q27. What is JWT?

JWT stands for JSON Web Token. It is a compact format for representing claims that can be signed or protected using cryptographic mechanisms.

A JWT commonly contains three encoded parts:

header.payload.signature

A signed JWT is not automatically encrypted. Do not put passwords or other confidential information in its payload. Verify tokens and their claims on the server.

Q28. How should passwords be stored?

Store passwords using a dedicated password-hashing algorithm such as Argon2id or bcrypt. Never store plain-text passwords.

const bcrypt = require('bcryptjs');

async function verifyPassword(enteredPassword, storedHash) {
    return bcrypt.compare(enteredPassword, storedHash);
}
Q29. What are environment variables?

Environment variables store configuration values outside the source code, such as the server port and database connection settings.

const PORT = process.env.PORT || 3000;

Never commit real credentials or signing secrets to a public repository.

Section 7: Performance and Deployment

Q30. Is Node.js single-threaded?

JavaScript execution in a typical Node.js application runs on a main thread, but Node.js also uses runtime facilities, operating-system I/O, and a worker pool for certain operations. Worker threads can execute JavaScript in separate threads.

Q31. What is the difference between synchronous and asynchronous code?

Synchronous operations run in sequence and may block further execution until they finish. Asynchronous operations allow other work to proceed while waiting for completion.

// Synchronous file read
const fs = require('node:fs');

const data = fs.readFileSync('message.txt', 'utf8');
console.log(data);

// Asynchronous file read
fs.readFile('message.txt', 'utf8', (err, content) => {
    if (err) {
        console.error(err);
        return;
    }

    console.log(content);
});
Q32. What are streams?

Streams process data in chunks instead of requiring the entire data set to be loaded into memory at once. They are useful for large files and data transfer.

const fs = require('node:fs');

const readStream = fs.createReadStream('large-file.txt');

readStream.on('data', chunk => {
    console.log('Received a chunk');
});

readStream.on('error', error => {
    console.error(error.message);
});
Q33. What is deployment?

Deployment is the process of making an application available in a target environment, such as a cloud hosting platform or a VPS.

A typical deployment includes installing dependencies, configuring environment variables, starting the server, and checking application logs.

Section 8: Coding Interview Questions

Q34. Write a function to reverse a string.
function reverseString(text) {
    return text.split('').reverse().join('');
}

console.log(reverseString('Node.js'));

Output: sj.edoN

Q35. Write a function to check whether a number is even or odd.
function checkNumber(number) {
    if (number % 2 === 0) {
        return 'Even';
    }

    return 'Odd';
}

console.log(checkNumber(10));
console.log(checkNumber(7));

Output:

Even
Odd
Q36. Find the largest number in an array.
function findLargest(numbers) {
    if (numbers.length === 0) {
        return undefined;
    }

    return Math.max(...numbers);
}

console.log(findLargest([10, 50, 20, 80, 30]));

Output: 80

Q37. Remove duplicate values from an array.
function removeDuplicates(numbers) {
    return [...new Set(numbers)];
}

console.log(removeDuplicates([1, 2, 2, 3, 4, 4]));

Output: [1, 2, 3, 4]

Q38. Count the vowels in a string.
function countVowels(text) {
    const matches = text.match(/[aeiou]/gi);
    return matches ? matches.length : 0;
}

console.log(countVowels('JavaScript'));

Output: 3

Section 9: Important Interview Tips

Prepare Before Your Interview
  • Understand the event loop and asynchronous programming.
  • Practice callbacks, Promises, and async/await.
  • Build REST APIs with Express.
  • Understand HTTP methods and status codes.
  • Practice database queries and parameterized SQL.
  • Understand authentication, authorization, and password hashing.
  • Learn environment variables and deployment basics.
  • Practice writing small JavaScript functions without assistance.
  • Explain your project decisions clearly.

Section 10: Final Revision Checklist

Use this checklist to review the topics you have learned.

Course Complete! You have reached Lesson 50 of 50. Keep practicing by building real applications, testing APIs, and explaining your code in your own words.

Final Quiz – Node.js Interview Preparation

Answer all three questions to test your understanding.

1. Which method is commonly used to handle a Promise's successful result?

2. Which Express middleware parses JSON request bodies?

3. What is the recommended way to store user passwords?