Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Node.js Documentation

JavaScript on the server — modules, npm, files, async programming and HTTP servers with Express.

Node.js runs JavaScript outside the browser — on servers, in command-line tools and build tools. It is built on Chrome's V8 engine and uses a non-blocking, event-driven model that handles thousands of connections efficiently. With Express and MongoDB it forms the backend of the MERN stack.

1. Introduction & Installation

Download the LTS version from nodejs.org (or use nvm to manage versions). It includes npm, the package manager.

node --version
npm --version
node app.js           # run a file
node                  # interactive REPL (Ctrl + C twice to exit)
node --watch app.js   # restart automatically on changes (Node 18+)
// app.js
console.log("Hello, Codify!");
console.log(`Node ${process.version} on ${process.platform}`.length > 0);

Output:

Hello, Codify!
true

⚠️ Common error: Cannot find module 'C:\...\app.js' — you ran node from the wrong folder. cd into the project folder first.

2. Modules

Node has two module systems. CommonJS (require) is the classic default; ES Modules (import) are used when package.json has "type": "module" or files end with .mjs.

// math.js (CommonJS)
const add = (a, b) => a + b;
const PI = 3.14159;
module.exports = { add, PI };

// app.js
const { add, PI } = require("./math");
const path = require("node:path");          // built-in module
console.log(add(2, 3), PI, path.extname("notes.pdf"));
// ES Modules version (package.json: "type": "module")
// math.js
export const add = (a, b) => a + b;
export default function square(x) { return x * x; }
// app.js
import square, { add } from "./math.js";
import fs from "node:fs/promises";

Useful built-in modules: fs (files), path, http, os, events, crypto, url, child_process, stream, util.

const os = require("node:os");
const path = require("node:path");
console.log(path.join("src", "routes", "user.js").replace(/\\/g, "/"));
console.log(path.basename("/docs/node.md", ".md"), typeof os.cpus().length);

Output:

src/routes/user.js
node number

⚠️ Common error: SyntaxError: Cannot use import statement outside a module — add "type": "module" to package.json or use require. Also, ES modules need the file extension in relative imports (./math.js).

3. npm & package.json

npm init -y                      # create package.json
npm install express              # dependency (saved in package.json)
npm install -D nodemon           # dev dependency
npm install                      # install everything listed (after cloning a project)
npm run dev                      # run a script
npx create-vite@latest           # run a package without installing it globally
npm outdated && npm update
npm uninstall nodemon
{
  "name": "codify-api",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "nodemon src/index.js",
    "start": "node src/index.js"
  },
  "dependencies": { "express": "^4.21.2" },
  "devDependencies": { "nodemon": "^3.1.9" }
}
  • node_modules/ holds installed packages — never commit it (add it to .gitignore).
  • package-lock.json pins exact versions — do commit it.
  • Version ranges: ^4.21.2 allows 4.x.x updates, ~4.21.2 only 4.21.x.

⚠️ Common error: Error: Cannot find module 'express' — run npm install in the project folder.

4. The File System

const fs = require("node:fs");
const fsp = require("node:fs/promises");
const path = require("node:path");

const file = path.join(__dirname, "notes.txt");

fs.writeFileSync(file, "line 1\n");                 // sync: blocks (fine in scripts)
fs.appendFileSync(file, "line 2\n");
console.log(fs.readFileSync(file, "utf8").trim().split("\n"));

async function main() {                              // async: preferred in servers
  await fsp.writeFile(file, JSON.stringify({ visits: 3 }));
  const data = JSON.parse(await fsp.readFile(file, "utf8"));
  console.log("visits:", data.visits, fs.existsSync(file));
  await fsp.unlink(file);                            // delete
  console.log("exists after delete:", fs.existsSync(file));
}
main();

Output:

[ 'line 1', 'line 2' ]
visits: 3 true
exists after delete: false

⚠️ Common error: ENOENT: no such file or directory — relative paths are relative to where you ran node, not the file. Use path.join(__dirname, ...) (or import.meta.dirname in ES modules).

5. Asynchronous Programming

Node never waits for slow I/O — it starts it and continues; the result arrives later via a callback, promise or async/await.

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

// 1. Callback style (older APIs): error-first callbacks
fs.readFile(__filename, "utf8", (err, text) => {
  if (err) return console.error(err);
  console.log("3. callback finished:", text.length > 0);
});

// 2. Promise / async-await (modern)
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function run() {
  await wait(50);
  console.log("4. after 50 ms");
  const results = await Promise.all([wait(10).then(() => "a"), wait(20).then(() => "b")]);
  console.log("5. parallel:", results);
}

console.log("1. start");
run();
console.log("2. end of synchronous code");

Output:

1. start
2. end of synchronous code
3. callback finished: true
4. after 50 ms
5. parallel: [ 'a', 'b' ]

The event loop phases: timers (setTimeout) → I/O callbacks → setImmediate → close callbacks. Between them, process.nextTick and promise callbacks (microtasks) always run first.

setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");
sync
nextTick
promise
timeout
immediate

(The order of timeout and immediate in the main module can vary; the first three lines never change.)

EventEmitter is the base of many Node APIs:

const EventEmitter = require("node:events");
const orders = new EventEmitter();
orders.on("placed", (id, total) => console.log(`Order ${id} placed: ₹${total}`));
orders.once("placed", () => console.log("First order bonus!"));
orders.emit("placed", 101, 499);
orders.emit("placed", 102, 250);
Order 101 placed: ₹499
First order bonus!
Order 102 placed: ₹250

⚠️ Common error: CPU-heavy loops (like hashing millions of items) block the event loop and freeze the whole server. Move them to worker_threads or a job queue.

6. HTTP Servers

The built-in http module:

const http = require("node:http");

const server = http.createServer((req, res) => {
  if (req.url === "/api/hello" && req.method === "GET") {
    res.writeHead(200, { "Content-Type": "application/json" });
    return res.end(JSON.stringify({ message: "Hello from Node" }));
  }
  res.writeHead(404, { "Content-Type": "text/plain" });
  res.end("Not found");
});

server.listen(3000, () => console.log("http://localhost:3000"));

Output (open http://localhost:3000/api/hello):

{"message":"Hello from Node"}

7. Express.js

Express makes routing, middleware and JSON easy:

npm install express cors dotenv
// index.js
require("dotenv").config();                 // loads variables from .env
const express = require("express");
const cors = require("cors");

const app = express();
app.use(cors());                            // allow requests from your React app
app.use(express.json());                    // parse JSON bodies

let todos = [{ id: 1, text: "Learn Express", done: false }];

app.get("/api/todos", (req, res) => res.json(todos));

app.get("/api/todos/:id", (req, res) => {
  const todo = todos.find((t) => t.id === Number(req.params.id));
  if (!todo) return res.status(404).json({ message: "Todo not found" });
  res.json(todo);
});

app.post("/api/todos", (req, res) => {
  const text = String(req.body.text || "").trim();
  if (!text) return res.status(400).json({ message: "text is required" });
  const todo = { id: Date.now(), text, done: false };
  todos.push(todo);
  res.status(201).json(todo);
});

app.delete("/api/todos/:id", (req, res) => {
  todos = todos.filter((t) => t.id !== Number(req.params.id));
  res.status(204).end();
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`API on http://localhost:${PORT}`));

Output (curl http://localhost:5000/api/todos):

[{"id":1,"text":"Learn Express","done":false}]

Middleware functions run in order for each request — logging, auth, validation, error handling:

const logger = (req, res, next) => {
  console.log(req.method, req.url);
  next();                                       // pass control to the next handler
};

const requireAuth = (req, res, next) => {
  if (req.headers.authorization !== "Bearer secret-token")
    return res.status(401).json({ message: "Login required" });
  next();
};

app.use(logger);
app.get("/api/profile", requireAuth, (req, res) => res.json({ name: "Asha" }));

// error-handling middleware has 4 arguments and goes last
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ message: "Something went wrong" });
});

Organise bigger apps with express.Router() (e.g. routes/todos.js), controllers and models.

⚠️ Common error: req.body is undefined — add app.use(express.json()) before your routes. And Cannot set headers after they are sent means you called res.json() twice — return after sending.

8. Working with Databases

MongoDB with Mongoose (the MERN way):

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema(
  {
    name: { type: String, required: true, trim: true },
    email: { type: String, required: true, unique: true, lowercase: true },
    role: { type: String, enum: ["user", "admin"], default: "user" },
  },
  { timestamps: true }
);
const User = mongoose.model("User", userSchema);

async function main() {
  await mongoose.connect(process.env.MONGO_URI);
  const user = await User.create({ name: "Asha", email: "asha@example.com" });
  const admins = await User.find({ role: "admin" }).sort({ createdAt: -1 }).limit(10);
  await User.updateOne({ _id: user._id }, { $set: { role: "admin" } });
  console.log(admins.length);
}

For SQL databases use pg (PostgreSQL), mysql2, or an ORM like Prisma. Always keep the connection string in an environment variable, never in code.

9. Environment, Security & Authentication

# .env  (add .env to .gitignore!)
PORT=5000
MONGO_URI=mongodb+srv://user:pass@cluster/db
JWT_SECRET=a-long-random-string

Password hashing and JWT login:

const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");

async function register(password) {
  return bcrypt.hash(password, 10);                       // store only the hash
}

async function login(user, password) {
  const ok = await bcrypt.compare(password, user.passwordHash);
  if (!ok) throw new Error("Invalid email or password");
  return jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "7d" });
}

function protect(req, res, next) {
  const token = req.headers.authorization?.split(" ")[1];
  try {
    req.userId = jwt.verify(token, process.env.JWT_SECRET).id;
    next();
  } catch {
    res.status(401).json({ message: "Invalid or expired token" });
  }
}

Security checklist: helmet (security headers), express-rate-limit (brute force), validate input (zod/joi), sanitise MongoDB queries, CORS only for your front-end origin, HTTPS in production, and never log secrets.

⚠️ Common error: committing .env to GitHub leaks your database password and secrets. Add it to .gitignore and rotate any leaked keys immediately.

10. Advanced Concepts

Streams process data piece by piece (big files, video, uploads) without loading everything into memory:

const fs = require("node:fs");
const zlib = require("node:zlib");
const { pipeline } = require("node:stream/promises");

async function compress() {
  fs.writeFileSync("big.txt", "codify ".repeat(10000));
  await pipeline(fs.createReadStream("big.txt"), zlib.createGzip(), fs.createWriteStream("big.txt.gz"));
  const before = fs.statSync("big.txt").size;
  const after = fs.statSync("big.txt.gz").size;
  console.log(before, after < before);
  fs.unlinkSync("big.txt");
  fs.unlinkSync("big.txt.gz");
}
compress();
70000 true

Other important topics

  • process.env, process.argv (command-line args), process.exit(code).
  • crypto.randomUUID(), crypto.createHash("sha256").
  • worker_threads for CPU-heavy work, cluster/PM2 to use all CPU cores.
  • Real-time apps with WebSockets (socket.io).
  • Testing with the built-in node:test runner, Jest or Vitest; API tests with Supertest.
  • Deploy on Render/Railway/Fly.io; set environment variables in the dashboard.
const crypto = require("node:crypto");
const hash = crypto.createHash("sha256").update("codify").digest("hex");
console.log(hash.length, crypto.randomUUID().split("-").length);
64 5

11. Examples with Output

Example 1 — Command-line word counter

const text = "the quick brown fox jumps over the lazy dog the end";
const counts = {};
for (const w of text.split(/\s+/)) counts[w] = (counts[w] || 0) + 1;
const top = Object.entries(counts).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 3);
console.log(top);
[ [ 'the', 3 ], [ 'brown', 1 ], [ 'dog', 1 ] ]

Example 2 — Read JSON, transform, write JSON

const fs = require("node:fs");
fs.writeFileSync("students.json", JSON.stringify([{ name: "Asha", marks: 91 }, { name: "Ravi", marks: 64 }]));

const students = JSON.parse(fs.readFileSync("students.json", "utf8"));
const result = students.map((s) => ({ ...s, passed: s.marks >= 70 }));
fs.writeFileSync("result.json", JSON.stringify(result, null, 2));
console.log(result.filter((s) => s.passed).map((s) => s.name));
fs.unlinkSync("students.json");
fs.unlinkSync("result.json");
[ 'Asha' ]

Example 3 — Retry an async task

async function retry(fn, attempts = 3) {
  for (let i = 1; i <= attempts; i++) {
    try {
      return await fn(i);
    } catch (err) {
      console.log(`attempt ${i} failed: ${err.message}`);
      if (i === attempts) throw err;
    }
  }
}

retry(async (i) => {
  if (i < 3) throw new Error("server busy");
  return "connected";
}).then((r) => console.log(r));
attempt 1 failed: server busy
attempt 2 failed: server busy
connected

12. Practice Problems

  1. Write a CLI script that reads a file name from process.argv[2] and prints its line, word and character counts.
  2. Build a REST API for notes (CRUD) with Express and an in-memory array; test it with Postman or curl.
  3. Add validation and proper status codes (400, 404, 201) to that API.
  4. Connect it to MongoDB with Mongoose and add pagination (?page=2&limit=10).
  5. Add user registration and login with bcrypt + JWT, and protect the notes routes.
  6. Add rate limiting and helmet; move secrets to .env.
  7. Build a file upload endpoint with multer that only accepts images under 2 MB.
  8. Connect your API to a React front-end and deploy the backend on Render.

13. Interview Questions

1. What is Node.js and why is it fast for I/O? A JavaScript runtime on V8. It uses a single-threaded event loop with non-blocking I/O (via libuv), so one process can serve many concurrent connections.

2. Explain the event loop. Node runs your synchronous code, then repeatedly processes queued callbacks in phases (timers, pending I/O, poll, check/setImmediate, close), running microtasks (nextTick, promises) between them.

3. process.nextTick vs setImmediate vs setTimeout(fn, 0)? nextTick runs right after the current operation (before promises); setTimeout(0) runs in the timers phase; setImmediate runs in the check phase after I/O.

4. CommonJS vs ES Modules? CommonJS uses require/module.exports and loads synchronously; ESM uses import/export, is statically analysable and loads asynchronously. Enable ESM with "type": "module".

5. What is middleware in Express? A function (req, res, next) that runs in the request pipeline — it can modify req/res, end the response, or call next() to continue.

6. How do you handle errors in async Express routes? Wrap handlers in try/catch or an asyncHandler that forwards rejections to next(err), and add a final error-handling middleware (err, req, res, next).

7. What are streams? Objects that read/write data in chunks (Readable, Writable, Duplex, Transform) — memory-efficient for large data; combine them with pipeline.

8. dependencies vs devDependencies? dependencies are needed at runtime; devDependencies only for development/building/testing (e.g. nodemon, jest).

9. How do you scale a Node app? Run multiple processes (cluster, PM2) behind a load balancer, keep servers stateless (sessions in Redis/JWT), cache, and offload CPU work to workers or queues.

10. How do you secure an Express API? Hash passwords, use JWT/sessions correctly, validate and sanitise input, rate-limit, helmet headers, restrict CORS, keep secrets in env vars, use HTTPS.

14. Cheat Sheet & References

CLI and npm

# run, watch, install, scripts
node app.js
node --watch app.js
npm init -y
npm i express mongoose dotenv
npm i -D nodemon
npm run dev
npx some-tool

Modules and paths

const fs = require("node:fs"); module.exports = { fn };
import express from "express"; export default app;
path.join(__dirname, "public"); path.extname(file); path.basename(file);
process.env.PORT; process.argv.slice(2); process.exit(1);

Files

fs.readFileSync(file, "utf8"); fs.writeFileSync(file, data);
await fsp.readFile(file, "utf8"); await fsp.writeFile(file, data);
await fsp.mkdir(dir, { recursive: true }); fs.existsSync(file);

Express

const app = express(); app.use(express.json()); app.use(cors());
app.get("/api/items", (req, res) => res.json(items));
app.post("/api/items", (req, res) => res.status(201).json(req.body));
req.params.id; req.query.page; req.body.name; req.headers.authorization;
res.status(404).json({ message: "Not found" });
const router = express.Router(); app.use("/api/users", router);
app.listen(5000, () => console.log("running"));

Async

await Promise.all([a(), b()]); await Promise.allSettled(list);
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
emitter.on("event", fn); emitter.emit("event", data);

Mongoose

await mongoose.connect(process.env.MONGO_URI);
const User = mongoose.model("User", new mongoose.Schema({ name: String }));
await User.create(doc); await User.find(filter).sort({ createdAt: -1 }).limit(10);
await User.findById(id); await User.updateOne(filter, { $set: data }); await User.deleteOne(filter);

Official documentation