Revise important Node.js concepts, JavaScript asynchronous programming, Express.js, REST APIs, databases, authentication, and deployment through these interview questions and answers.
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.
No. JavaScript is the programming language, while Node.js is a runtime environment for executing JavaScript outside the browser.
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
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"
}
}
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.
A module is a reusable unit of code. Modules help developers organize applications into separate files and components.
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
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.
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.
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);
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.
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!
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.
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));
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();
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.
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);
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.
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 |
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');
});
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.
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.
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.
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]
);
Authentication verifies a user's identity, for example by checking credentials during login.
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.
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.
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);
}
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.
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.
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);
});
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);
});
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.
function reverseString(text) {
return text.split('').reverse().join('');
}
console.log(reverseString('Node.js'));
Output: sj.edoN
function checkNumber(number) {
if (number % 2 === 0) {
return 'Even';
}
return 'Odd';
}
console.log(checkNumber(10));
console.log(checkNumber(7));
Output:
Even
Odd
function findLargest(numbers) {
if (numbers.length === 0) {
return undefined;
}
return Math.max(...numbers);
}
console.log(findLargest([10, 50, 20, 80, 30]));
Output: 80
function removeDuplicates(numbers) {
return [...new Set(numbers)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4]));
Output: [1, 2, 3, 4]
function countVowels(text) {
const matches = text.match(/[aeiou]/gi);
return matches ? matches.length : 0;
}
console.log(countVowels('JavaScript'));
Output: 3
Use this checklist to review the topics you have learned.
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?