# Node.js Cheat Sheet

Course: [Node.js](https://www.devtutorials.ai/learn/nodejs) · Section: Project and Reference
Source: https://www.devtutorials.ai/learn/nodejs/project-reference/cheat-sheet

> A one-page Node.js reference: core modules, CommonJS and ES module patterns, event loop order, process, fs and path, EventEmitter, streams and buffers, HTTP and networking, child processes and workers, node:test, crypto, CLI flags, package.json fields and npm commands, plus common error codes, error messages with fixes, and a glossary for beginners.

## Node.js Cheat Sheet

Every important Node.js API from this course, on one page.

- Each table names the lesson that teaches it.
- Code uses ES modules (`import`) unless it says CommonJS.
- Keep this page open while you build your own projects.

## Core Modules Quick Reference

| Module | What it does | Lesson |
|---|---|---|
| `node:fs/promises` | Read, write and manage files | Path and File System |
| `node:path` | Build and split file paths | Path and File System |
| `node:events` | `EventEmitter`, `once`, `on` | Events and Utilities |
| `node:util` | `promisify`, `parseArgs`, `inspect`, `debuglog` | Events and Utilities |
| `node:stream` | Readable, Writable, Transform, `pipeline` | Buffers, Streams and Compression |
| `node:readline` | Read lines from files and stdin | Buffers, Streams and Compression |
| `node:zlib` | gzip, deflate, Brotli | Buffers, Streams and Compression |
| `node:http` | HTTP servers and clients | HTTP and Networking |
| `node:net` | TCP sockets | HTTP and Networking |
| `node:child_process` | Run other programs | Child Processes, Worker Threads and Clustering |
| `node:worker_threads` | Run JavaScript on more threads | Child Processes, Worker Threads and Clustering |
| `node:test`, `node:assert/strict` | Tests and checks | Testing with the Built-in Test Runner |
| `node:crypto` | Hashes, HMAC, random values, encryption | Cryptography and Security |
| `node:os` | Facts about the computer | Process, OS and CLI Tools |

## Module Patterns

```js
// ES module (.mjs, or .js with "type": "module")
import fs from "node:fs/promises";
import { average } from "./grades.js";        // full file name needed
import data from "./data.json" with { type: "json" };
export function grade(m) { return m >= 90 ? "A" : "B"; }
export default grade;
const later = await import("./big-module.js"); // dynamic import, top-level await
console.log(import.meta.dirname, import.meta.filename);
```

```js
// CommonJS (.cjs, or .js without "type": "module")
const fs = require("node:fs");
const { average } = require("./grades");      // .js can be left out
module.exports = { grade };                    // never: exports = { ... }
console.log(__dirname, __filename, require.main === module);
```

| Task | Code | Lesson |
|---|---|---|
| Use `require` inside ESM | `const require = createRequire(import.meta.url)` | Modules in Node.js |
| Run TypeScript | `node app.ts` (types are stripped, not checked) | Modules in Node.js |
| Package entry points | `"exports": { ".": "./index.js", "./grades": "./grades.js" }` | Packages and npm |
| Private short names | `"imports": { "#config": "./src/config.js" }` | Packages and npm |

## Event Loop Order

1. All **sync code** from top to bottom.
2. **`process.nextTick`** callbacks.
3. **Promise** callbacks and `queueMicrotask`.
4. **Timers** phase: `setTimeout`, `setInterval`.
5. **Poll** phase: file and network callbacks.
6. **Check** phase: `setImmediate`.
7. **Close** callbacks. Then back to step 4. Steps 2 and 3 run again after every callback.

| Task | Code | Lesson |
|---|---|---|
| Wait with await | `await setTimeout(500)` from `node:timers/promises` | Event Loop and Timers |
| Let the loop breathe | `setImmediate(() => nextPiece())` | Event Loop and Timers |
| Do not keep the program alive | `timer.unref()` | Event Loop and Timers |
| Thread pool size | `UV_THREADPOOL_SIZE=8 node app.js` | Event Loop and Timers |

## process Methods

| Task | Code | Lesson |
|---|---|---|
| Command words | `process.argv.slice(2)` | Process, OS and CLI Tools |
| Settings | `process.env.PORT ?? "3000"` | Process, OS and CLI Tools |
| Load a `.env` file | `node --env-file=.env app.js` or `process.loadEnvFile()` | Process, OS and CLI Tools |
| Write without new line | `process.stdout.write("Loading...")` | Process, OS and CLI Tools |
| Fail at the end | `process.exitCode = 1` | Process, OS and CLI Tools |
| Stop now | `process.exit(1)` | Process, OS and CLI Tools |
| Clean up on Ctrl + C | `process.on("SIGINT", cleanup)` | Process, OS and CLI Tools |
| Polite stop | `process.on("SIGTERM", shutdown)` | Production Readiness |
| Folder started from | `process.cwd()` | Process, OS and CLI Tools |
| Memory and CPU | `process.memoryUsage()`, `process.cpuUsage()` | Debugging and Profiling |
| Last safety net | `process.on("uncaughtException", logAndExit)` | Error Handling |

## fs and path Patterns

```js
import { readFile, writeFile, mkdir, readdir, rename, rm, stat } from "node:fs/promises";
import path from "node:path";

const file = path.join(import.meta.dirname, "data", "marks.csv");
const text = await readFile(file, "utf8");                     // text
const json = JSON.parse(await readFile("config.json", "utf8")); // JSON
await mkdir("reports/2026", { recursive: true });
await writeFile("report.json.tmp", JSON.stringify(json));       // safe write:
await rename("report.json.tmp", "report.json");                 // temp, then rename
const entries = await readdir("reports", { withFileTypes: true });
const info = await stat("report.json");                         // info.size, info.mtime
await rm("old", { recursive: true, force: true });
```

| Task | Code | Lesson |
|---|---|---|
| Glue path parts | `path.join("a", "b", "c.txt")` | Path and File System |
| Absolute path | `path.resolve("reports")` | Path and File System |
| Name, folder, extension | `path.basename(p)`, `path.dirname(p)`, `path.extname(p)` | Path and File System |
| URL to path | `fileURLToPath(import.meta.url)` | Path and File System |
| Write only if new | `writeFile(p, data, { flag: "wx" })` | Path and File System |

## EventEmitter Patterns

```js
import { EventEmitter, once } from "node:events";

class Classroom extends EventEmitter {
  join(name) { this.emit("joined", name); }
}
const room = new Classroom();
room.on("joined", (name) => console.log("Hello", name));   // every time
room.once("joined", () => console.log("First student!"));  // one time
room.on("error", (err) => console.error(err.message));     // always handle error
const [name] = await once(room, "joined");                  // wait for one event
```

## Stream and Buffer Patterns

```js
import { createReadStream, createWriteStream } from "node:fs";
import { createInterface } from "node:readline";
import { pipeline } from "node:stream/promises";
import { Transform } from "node:stream";
import { createGzip } from "node:zlib";

for await (const line of createInterface({ input: createReadStream("big.csv") })) { /* one line */ }
await pipeline(createReadStream("log.txt"), createGzip(), createWriteStream("log.txt.gz"));
const upper = new Transform({ transform(chunk, enc, done) { done(null, chunk.toString().toUpperCase()); } });

const buf = Buffer.from("Hi");               // <Buffer 48 69>
buf.toString("base64");                      // "SGk="
Buffer.from("SGk=", "base64").toString();    // "Hi"
```

| Task | Code | Lesson |
|---|---|---|
| Backpressure | `if (!out.write(chunk)) await once(out, "drain")` | Buffers, Streams and Compression |
| Stream from a list | `Readable.from(["a", "b"])` | Buffers, Streams and Compression |
| Copy part of a buffer | `Buffer.from(buf.subarray(0, 4))` | Buffers, Streams and Compression |

## HTTP and Networking Patterns

```js
import http from "node:http";

const server = http.createServer(async (req, res) => {
  const { pathname, searchParams } = new URL(req.url, "http://localhost");
  if (req.method === "POST") {
    let body = "";
    for await (const chunk of req) body += chunk;
    res.writeHead(201, { "Content-Type": "application/json" });
    return res.end(JSON.stringify({ saved: JSON.parse(body) }));
  }
  if (pathname === "/health") return res.writeHead(200).end("ok");
  res.writeHead(404).end("Not found");
});
server.listen(3000);

const reply = await fetch("http://localhost:3000/health", { signal: AbortSignal.timeout(2000) });
```

| Task | Code | Lesson |
|---|---|---|
| Any free port | `server.listen(0)` then `server.address().port` | HTTP and Networking |
| Port busy | `server.on("error", (e) => e.code === "EADDRINUSE")` | HTTP and Networking |
| Serve a file | `createReadStream(file).pipe(res)` | HTTP and Networking |
| Stop gracefully | `server.close(callback)` + `closeIdleConnections()` | Production Readiness |

## Child Process and Worker Patterns

```js
import { execFile, spawn, fork } from "node:child_process";
import { promisify } from "node:util";
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";

const { stdout } = await promisify(execFile)("git", ["log", "--oneline", "-3"]); // no shell
const child = spawn("node", ["job.js"]); child.stdout.on("data", (d) => process.stdout.write(d));

if (isMainThread) {
  const w = new Worker(new URL(import.meta.url), { workerData: 1_000_000 });
  w.on("message", (result) => console.log(result));
} else {
  parentPort.postMessage(heavyMaths(workerData));
}
```

## node:test Patterns

```js
import { test, describe, it, beforeEach, mock } from "node:test";
import assert from "node:assert/strict";

describe("grade", () => {
  beforeEach(() => { /* fresh data */ });
  it("90 is an A", () => assert.equal(grade(90), "A"));
  it("objects", () => assert.deepStrictEqual({ a: [1] }, { a: [1] }));
  it("throws", () => assert.throws(() => parse("x"), TypeError));
  it("rejects", async () => { await assert.rejects(load(99), /not found/); });
});

test("mocks", (t) => {
  const notify = mock.fn();
  t.mock.timers.enable({ apis: ["setTimeout"] });
  t.mock.timers.tick(1000);
});
```

| Task | Command | Lesson |
|---|---|---|
| Run all tests | `node --test` | Testing with the Built-in Test Runner |
| Watch | `node --test --watch` | Testing with the Built-in Test Runner |
| Coverage | `node --test --experimental-test-coverage` | Testing with the Built-in Test Runner |

## crypto Patterns

```js
import { createHash, createHmac, randomBytes, randomUUID, scrypt, timingSafeEqual } from "node:crypto";

createHash("sha256").update("data").digest("hex");            // fingerprint
createHmac("sha256", process.env.SECRET).update(msg).digest("hex"); // signature
randomBytes(32).toString("hex");                               // token
randomUUID();                                                  // id
// passwords: salt + scrypt (or pbkdf2) + timingSafeEqual
```

## CLI Flags

| Flag | What it does |
|---|---|
| `-v`, `--version` | Print the Node.js version |
| `-e "code"`, `-p "code"` | Run code, or run it and print the answer |
| `-c`, `--check` | Check a file for syntax errors |
| `--watch` | Restart when files change |
| `--env-file=.env` | Load settings into `process.env` |
| `--run <script>` | Run a `package.json` script quickly |
| `--test` | Run tests |
| `--inspect`, `--inspect-brk` | Allow a debugger to connect |
| `--enable-source-maps` | Show original file lines in errors |
| `--cpu-prof` | Write a CPU profile |
| `--max-old-space-size=2048` | Allow a bigger heap (MB) |
| `--permission`, `--allow-fs-read=dir` | Limit what the program may touch |
| `--trace-deprecation`, `--throw-deprecation` | Find or fail on deprecated APIs |
| `--report-on-fatalerror` | Write a diagnostic report on a fatal crash |

## package.json Fields

| Field | Example | What it does |
|---|---|---|
| `name`, `version` | `"report-card"`, `"1.2.0"` | Who the package is |
| `type` | `"module"` | `.js` files are ES modules |
| `main` | `"index.js"` | Entry file (old style) |
| `exports` | `{ ".": "./index.js" }` | Public entry points |
| `imports` | `{ "#config": "./src/config.js" }` | Private short names |
| `bin` | `{ "report-card": "./cli.js" }` | Command name for a CLI |
| `scripts` | `{ "test": "node --test" }` | Named commands |
| `engines` | `{ "node": ">=22" }` | Supported Node.js versions |
| `private` | `true` | Block `npm publish` |
| `files` | `["dist"]` | What gets published |
| `dependencies` / `devDependencies` | `{ "dayjs": "^1.11.0" }` | Packages needed to run / to build |

## npm Commands

| Command | What it does |
|---|---|
| `npm init -y` | Make a `package.json` |
| `npm install dayjs` | Add a dependency |
| `npm install -D typescript` | Add a dev dependency |
| `npm ci` | Clean, exact install from the lockfile |
| `npm run build -- --flag` | Run a script with arguments |
| `npx tsc --version` | Run a tool from `node_modules/.bin` |
| `npm ls`, `npm outdated`, `npm update` | Check and update packages |
| `npm audit`, `npm audit fix` | Find and fix known security problems |
| `npm link` | Install your CLI on your own computer |
| `npm pack --dry-run`, `npm publish` | Preview and publish a package |

## Troubleshooting

### Common Error Codes

| Code | Means | Fix |
|---|---|---|
| `ENOENT` | No such file or folder | Check the path. Build it from `import.meta.dirname` |
| `EACCES`, `EPERM` | Not allowed | Use a folder you own. Do not use `sudo npm` |
| `EEXIST` | Already exists | Use `{ recursive: true }` or another name |
| `EADDRINUSE` | Port already in use | Stop the other program, or use another port |
| `ECONNREFUSED` | Nothing is listening there | Start the server first, check the port |
| `ECONNRESET` | The other side hung up | Retry, check the other server's logs |
| `ETIMEDOUT` | No answer in time | Retry later, raise the timeout |
| `EMFILE` | Too many open files | Close files and handles, open fewer at once |
| `ERR_MODULE_NOT_FOUND` | Import path is wrong | Add the full file name, such as `./grades.js` |
| `ERR_REQUIRE_ESM` / `ERR_REQUIRE_ASYNC_MODULE` | `require` of an ES module that cannot be required | Use `import`, or remove top-level `await` |
| `ERR_IMPORT_ATTRIBUTE_MISSING` | JSON import without the attribute | Add `with { type: "json" }` |
| `ERR_PACKAGE_PATH_NOT_EXPORTED` | That file is not in the package's `exports` | Import a public path |
| `ERR_INVALID_ARG_TYPE` | Wrong type passed to a Node.js API | Check the value and its type |
| `ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX` | `enum` or similar in `node app.ts` | Use a union type or an object |

### Common Error Messages and Fixes

| Message | Likely cause | Fix |
|---|---|---|
| `require is not defined in ES module scope` | `require` in an ES module | Use `import`, or `createRequire` |
| `__dirname is not defined in ES module scope` | `__dirname` in an ES module | Use `import.meta.dirname` |
| `Cannot use import statement outside a module` | `import` in a CommonJS file | Add `"type": "module"` or rename to `.mjs` |
| `Cannot find module './grades'` | Wrong path or missing extension | Check the path and the extension |
| `'node' is not recognized` | Node.js not installed, or an old terminal | Install Node.js, open a new terminal |
| `JavaScript heap out of memory` | A leak, or too much data at once | Stream the data, find the leak, then raise the heap |
| `MaxListenersExceededWarning` | Listeners added again and again | Add listeners once, remove them with `off` |
| `Unhandled 'error' event` | An emitter failed with no listener | Add `on("error", ...)` |
| `write after end` | Writing to a finished stream | Do not write after `end()` |
| `Cannot set headers after they are sent` | Two responses for one request | `return` after sending a response |

## Glossary

| Term | Meaning |
|---|---|
| **Node.js** | A runtime that runs JavaScript outside the browser |
| **Runtime** | A program that runs code and gives it tools |
| **V8** | The engine that runs JavaScript inside Node.js and Chrome |
| **libuv** | The C library behind the event loop and the thread pool |
| **Event loop** | Picks the next callback to run, one at a time |
| **Non-blocking** | Start a slow job and carry on, handle the result later |
| **Callback** | A function you pass in, to be called later |
| **Promise** | An object for a result that comes later |
| **Module** | One file with its own scope and its own exports |
| **Package** | A folder of code with a `package.json`, shared with npm |
| **Dependency** | A package your project needs |
| **SemVer** | MAJOR.MINOR.PATCH version numbers |
| **Lockfile** | `package-lock.json`: the exact installed versions |
| **Environment variable** | A named setting given to a program from outside |
| **Exit code** | A number a program returns: 0 means success |
| **Signal** | A message from the operating system, such as SIGINT |
| **Buffer** | A box of raw bytes |
| **Stream** | Data handled a piece at a time |
| **Backpressure** | Slowing the writer down when the reader is behind |
| **EventEmitter** | An object that sends named events to listeners |
| **Socket** | One end of a two-way network connection |
| **Child process** | Another program started by your program |
| **Worker thread** | Another JavaScript thread in the same process |
| **Hash** | A fixed-size fingerprint of data |
| **Graceful shutdown** | Finish current work and close resources before exiting |
| **Health check** | A small URL that says whether the app is alive and ready |

## What to Remember

- Use this page to look things up, and the lessons to understand them.
- Start new projects with ES modules, `fs/promises` and `node --test`.
- When an error appears, check its `code` first, then this page's tables.

Next: **Introduction to Express.js** in the Express.js course. You will build web servers faster with a framework on top of everything you learned here.
