Node.js Cheatsheet

View saved

Node.js runs JavaScript outside the browser—great for CLIs, APIs, and tooling.

Prefer promises/async await, understand the event loop at a high level, and keep blocking work off the main thread.

Runtime & modules

node and npm

Run files with Node; manage packages with npm (or pnpm/yarn).

node app.js
npm init -y

ES modules

Use import/export when "type": "module" is set in package.json.

import fs from "node:fs/promises";
export function add(a, b) { return a + b; }

CommonJS

Older style with require / module.exports.

const fs = require("fs");
module.exports = { add };

node: protocol

Import built-ins with the node: prefix for clarity.

import path from "node:path";
import { fileURLToPath } from "node:url";

__dirname in ESM

Recreate __dirname when using ES modules.

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

npm & package.json

Install packages

Add runtime or dev dependencies.

npm install express
npm install -D nodemon

Scripts

Define commands in package.json scripts.

{
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js"
  }
}

npx

Run a package binary without a global install.

npx eslint .
npx --yes cowsay hi

Semantic versions

Understand ^ and ~ ranges; lockfile pins exact installs for CI.

npm ci

Async & files

async / await

Prefer promises APIs from node:fs/promises.

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

try / catch

Handle rejected promises around await.

try {
  await fs.readFile("missing.txt");
} catch (err) {
  console.error(err);
}

path.join

Build paths safely across operating systems.

const file = path.join(__dirname, "data", "file.txt");

process.env

Read environment variables; never hard-code secrets.

const port = Number(process.env.PORT ?? 3000);

HTTP peek

http.createServer

Minimal built-in server for learning.

import http from "node:http";

http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("ok");
}).listen(3000);

Express sketch

Popular framework for routing and middleware.

import express from "express";
const app = express();
app.get("/health", (req, res) => res.json({ ok: true }));
app.listen(3000);

JSON body

Parse JSON with middleware (Express) or manually from chunks.

app.use(express.json());
app.post("/echo", (req, res) => res.json(req.body));

Exit codes

Exit non-zero on fatal startup errors.

process.exitCode = 1;

Comments

One comment per signed-in account. Comments are saved with this page’s URL.