Node.js
Node.js
Core modules, Express, async/await, REST APIs, authentication, and deployment — complete Node.js reference.
📖 5 sections
⏰ 15 min read
✅ Quizzes included
01Node.js Core
NODECore modules
// File system
const fs = require("fs");
fs.readFile("./file.txt", "utf8", (err, data) => { console.log(data); });
const data = fs.readFileSync("./file.txt", "utf8"); // sync version
fs.writeFileSync("out.txt", "Hello");

// Path
const path = require("path");
path.join(__dirname, "public", "index.html");
path.extname("file.html");  // ".html"
path.basename("/path/to/file.js");  // "file.js"

// OS, HTTP, Events, Crypto - built in modules
const os = require("os");
const http = require("http");
const EventEmitter = require("events");
const crypto = require("crypto");
02Express.js
NODEExpress setup
const express = require("express");
const app = express();

// Middleware
app.use(express.json());          // parse JSON body
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public")); // serve static files

// Routes
app.get("/api/users", async (req, res) => {
  try {
    const users = await User.find();
    res.json({ users });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

app.post("/api/users", async (req, res) => {
  const user = await User.create(req.body);
  res.status(201).json({ user });
});

app.listen(5000, () => console.log("Server running"));
// Route params: /users/:id -> req.params.id
// Query string: /users?page=1 -> req.query.page
03Async/Await & Promises
NODEAsync patterns
// Promise chain
fetch("/api")
  .then(r => r.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

// Async/await (cleaner)
async function getData() {
  try {
    const res = await fetch("/api");
    const data = await res.json();
    return data;
  } catch (err) {
    console.error(err);
  }
}

// Parallel requests (faster)
const [users, courses] = await Promise.all([
  User.find(),
  Course.find()
]);

// Promise.allSettled: get all results even if some fail
const results = await Promise.allSettled([p1, p2, p3]);
❓ Quiz
What is the purpose of async/await?
async/await is syntactic sugar over Promises that makes asynchronous code read like synchronous code, improving readability without blocking the thread.
04MongoDB & Mongoose
NODEMongoose CRUD
const mongoose = require("mongoose");
await mongoose.connect(process.env.MONGO_URI);

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, unique: true },
  createdAt: { type: Date, default: Date.now }
});
const User = mongoose.model("User", userSchema);

// CREATE
const user = await User.create({ name: "Ali", email: "a@b.com" });
// READ
const users = await User.find({ name: "Ali" });
const user = await User.findById(id);
// UPDATE
await User.findByIdAndUpdate(id, { name: "Sara" }, { new: true });
// DELETE
await User.findByIdAndDelete(id);
05Authentication
NODEJWT auth pattern
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");

// Register
const hashed = await bcrypt.hash(password, 12);
await User.create({ email, password: hashed });

// Login
const user = await User.findOne({ email });
const match = await bcrypt.compare(password, user.password);
if (!match) return res.status(401).json({ error: "Invalid" });
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "7d" });
res.json({ token });

// Middleware protect
function protect(req, res, next) {
  const token = req.headers.authorization?.split(" ")[1];
  if (!token) return res.status(401).json({ error: "No token" });
  const decoded = jwt.verify(token, process.env.JWT_SECRET);
  req.user = decoded;
  next();
}