AZ.dev

Node.js Essentials Cheat Sheet

Node.js

The Node flags and core APIs you reach for every day, from watching a file to reading one, spawning a process, and debugging a hang.

12 cards | node: 22

Running things

Restart on every file change

node --watch server.js

Restarts when the entry file or anything it imports changes.

Load a .env file without a package

node --env-file=.env server.js

Node 20.6 and up. Vars already in the shell win over the file.

Run the built-in test runner

node --test

Finds *.test.js files. Write tests with import { test } from "node:test" and import assert from "node:assert/strict".

Files and paths

Read a file as text

import { readFile } from "node:fs/promises";

const text = await readFile("notes.md", "utf8");

Leave off "utf8" and you get a Buffer.

Get the directory of the current module

const configPath = path.join(import.meta.dirname, "config.json");

Node 20.11 and up. Before that: path.dirname(fileURLToPath(import.meta.url)).

Processes

Run a command and capture its output

import { execFile } from "node:child_process";
import { promisify } from "node:util";

const { stdout } = await promisify(execFile)("git", ["status", "--short"]);

execFile takes an argument array, so nothing in it goes through a shell.

Debugging

Pause on the first line and attach the debugger

node --inspect-brk server.js

Open chrome://inspect in Chrome. Plain --inspect attaches without pausing.

Time a block of code

console.time("query");
await db.query(sql);
console.timeEnd("query");

Prints query: 12.345ms. The label must match on both ends.