cluster deboistech.in Get started
Cheatsheet

Node.js

Node.js and npm for scripts and small servers: running code, modules, files, HTTP, async code and packages.

Practice this path

Run and manage

  • node app.js

    Run a script

  • node --watch app.js

    Restart when a file changes

  • node -e "console.log(process.version)"

    Run one line of code

  • node --test

    Run the built-in test runner on *.test.js files

  • node --inspect app.js

    Start with the debugger listening (open chrome://inspect)

npm

  • npm init -y

    Create a package.json

  • npm install express

    Add a dependency (npm i -D for dev tools)

  • npm ci

    Install exactly what package-lock.json says (use in CI and Docker)

  • npm run build

    Run a script from package.json

  • npm outdated  |  npm audit

    Packages with newer versions, and known vulnerabilities

  • npx prettier --write .

    Run a tool without installing it globally

  • { "scripts": { "start": "node server.js", "test": "node --test" } }

    Scripts in package.json: npm start, npm test

Modules

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

    CommonJS: load a module (built-ins have the node: prefix)

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

    ES modules: use "type": "module" in package.json or a .mjs file

  • module.exports = { add };  |  export const add = (a, b) => a + b;

    Export from CommonJS / from an ES module

  • const path = require("node:path"); path.join(__dirname, "data", "a.json")

    Build paths that work on every system

Files and process

  • const text = await fs.promises.readFile("a.txt", "utf8");

    Read a file

  • await fs.promises.writeFile("out.json", JSON.stringify(data, null, 2));

    Write a file

  • JSON.parse(text)  |  JSON.stringify(obj)

    Text to object and back

  • process.argv.slice(2)

    The command-line arguments

  • process.env.PORT || 3000

    An environment variable with a default

  • process.exit(1)

    Stop with an error code (0 means success)

Async code

  • const data = await fetch(url).then((r) => r.json());

    Fetch JSON (fetch is built in)

  • const [a, b] = await Promise.all([getA(), getB()]);

    Run two things at the same time and wait for both

  • try { await work(); } catch (err) { console.error(err.message); }

    Handle a failure in async code

  • setTimeout(() => console.log("later"), 1000);

    Run something after a delay (milliseconds)

  • process.on("unhandledRejection", (e) => { console.error(e); process.exit(1); });

    Do not let a forgotten rejection pass silently

A small HTTP server

  • const http = require("node:http");
    http.createServer((req, res) => {
      res.setHeader("Content-Type", "application/json");
      res.end(JSON.stringify({ ok: true, path: req.url }));
    }).listen(process.env.PORT || 3000);

    A server with no dependencies

  • curl -s localhost:3000/health

    Try it from another terminal

  • res.writeHead(404); res.end("not found");

    Reply with a status code

  • process.on("SIGTERM", () => server.close(() => process.exit(0)));

    Shut down cleanly when a container stops

Cheatsheet for the Node.js path · Deboistech · All cheatsheets