Back to Home
    Node.jsNode.js v22 LTSIntermediate

    Node.js

    Node.js modules, file system, HTTP servers, streams, events, and npm ecosystem essentials.

    10 min read
    nodejsjavascriptbackendruntime

    Modules

    1 topic

    ESM vs CommonJS

    javascript
    // ESM (modern — use this)
    import fs from "node:fs/promises";
    import { readFile, writeFile } from "node:fs/promises";
    export const greet = name => `Hello, ${name}`;
    export default class Server { /* ... */ }
    
    // CommonJS (legacy)
    const fs = require("fs");
    module.exports = { greet };
    
    // package.json — choose one:
    // "type": "module"   → .js files are ESM
    // "type": "commonjs" → .js files are CJS (default)
    // Use .mjs / .cjs to override per-file

    💡 New projects should use ESM (type: module)

    ⚡ Use node: prefix for built-ins to make them explicit

    File System

    1 topic

    fs/promises

    javascript
    import { readFile, writeFile, mkdir, readdir, stat, unlink } from "node:fs/promises";
    
    // Read file
    const content = await readFile("file.txt", "utf8");
    
    // Write file
    await writeFile("out.txt", "hello", "utf8");
    
    // Create directory
    await mkdir("logs", { recursive: true });
    
    // List directory
    const files = await readdir("./src");
    
    // File info
    const info = await stat("file.txt");
    info.size;         // bytes
    info.isDirectory(); // false
    
    // Delete
    await unlink("tmp.txt");

    💡 Always use fs/promises (async) — never the sync versions in a server

    ⚡ recursive: true in mkdir won't throw if dir already exists

    HTTP Server

    1 topic

    Built-in HTTP

    javascript
    import { createServer } from "node:http";
    
    const server = createServer((req, res) => {
      if (req.method === "GET" && req.url === "/health") {
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ status: "ok" }));
        return;
      }
      res.writeHead(404);
      res.end("Not Found");
    });
    
    server.listen(3000, () => {
      console.log("Server on http://localhost:3000");
    });
    
    // Graceful shutdown
    process.on("SIGTERM", () => server.close(() => process.exit(0)));

    💡 Handle SIGTERM for graceful shutdown in production/containers

    Events & Streams

    1 topic

    EventEmitter

    javascript
    import { EventEmitter } from "node:events";
    
    class JobQueue extends EventEmitter {
      add(job) {
        this.emit("job:added", job);
        this.process(job);
      }
      async process(job) {
        try {
          const result = await job.run();
          this.emit("job:done", { job, result });
        } catch (err) {
          this.emit("job:error", { job, err });
        }
      }
    }
    
    const queue = new JobQueue();
    queue.on("job:done", ({ job, result }) => console.log(result));
    queue.on("error", err => console.error(err)); // Always handle error!

    ⚠️ Always listen to the 'error' event — unhandled errors crash the process

    Related Articles

    Background reading and deeper explanations for this sheet.

    Event-Driven Agents with Kafka Streams: A Practical Guide for Building Real-Time AI Workflows

    Event-driven agents let you move from slow, request/response automation to responsive systems that react in milliseconds to real-world signals. In this hands-on guide, you’ll learn how to design, build, and operate agentic workflows using Apache Kafka and Kafka Streams, with practical patterns, code snippets, and production-ready advice.

    keyword overlap

    GenAI SaaS Architecture: A Practical Blueprint for Building, Scaling, and Securing AI Products

    Designing a SaaS product on top of GenAI is more than calling an LLM API—it requires thoughtful architecture across product, data, safety, and operations. This practical guide walks you through a beginner-friendly yet deep system blueprint, with real-world patterns, code snippets, and deployment strategies you can use immediately.

    keyword overlap

    How to Design a Production-Ready LLM System: A Practical Guide for Real-World Apps

    Building an LLM demo is easy. Running one reliably in production is not. This guide walks you through architecture, retrieval, evaluation, safety, and operations so you can ship LLM systems that are useful, secure, and maintainable at scale.

    keyword overlap

    How to Design a Production-Ready LLM System: Architecture, Guardrails, and Scale

    Building an LLM demo is easy; building one that survives real traffic, strict latency targets, and compliance audits is not. This guide walks through a real production architecture, design decisions, and implementation patterns for reliable, secure, and cost-efficient LLM systems.

    keyword overlap