Skip to main content

Node.js Cheatsheet

Backend 16 views Apr 2026

Node.js Cheatsheet

Core Globals

__filename       // absolute path of current file
__dirname        // directory of current file
process.env      // environment variables
process.argv     // command-line args array
process.exit(0)  // exit with code
process.cwd()    // current working directory
process.pid      // process ID
process.version  // Node version string

console.log("info")
console.error("error")
console.warn("warn")
console.time("label")
console.timeEnd("label")
console.table([{a:1},{a:2}])

Modules (CommonJS)

// Export
module.exports = { add, sub };
module.exports = function MyClass() {};
exports.helper = function() {};

// Import
const fs = require("fs");
const { add, sub } = require("./math");
const MyClass = require("./my-class");

// ES Modules (add "type":"module" to package.json)
import fs from "fs";
import { add } from "./math.js";
export const PI = 3.14;
export default class App {}

File System (fs)

const fs = require("fs");
const fsp = require("fs").promises;   // promise API

// Async (callback)
fs.readFile("file.txt", "utf8", (err, data) => {
  if (err) throw err;
  console.log(data);
});

fs.writeFile("out.txt", "content", err => { if(err) throw err; });

// Promise API (recommended)
const data = await fsp.readFile("file.txt", "utf8");
await fsp.writeFile("out.txt", data);
await fsp.appendFile("log.txt", "line\n");
await fsp.unlink("file.txt");        // delete
await fsp.rename("a.txt","b.txt");
await fsp.mkdir("newdir", { recursive: true });
const files = await fsp.readdir(".");
const stat = await fsp.stat("file.txt");
stat.size; stat.mtime; stat.isDirectory();

// Sync (use only at startup)
const content = fs.readFileSync("file.txt", "utf8");
fs.writeFileSync("out.txt", "data");

Path

const path = require("path");

path.join("/usr", "local", "bin")    // /usr/local/bin
path.resolve("src", "index.js")      // absolute path
path.dirname("/usr/local/bin")       // /usr/local
path.basename("/usr/local/bin")      // bin
path.basename("/app/index.js",".js") // index
path.extname("file.txt")             // .txt
path.isAbsolute("/usr/bin")          // true

// path.parse returns object with root, dir, base, ext, name
// e.g. path.parse("/usr/local/bin.sh")
// => root="/", dir="/usr/local", base="bin.sh", ext=".sh", name="bin"

path.format({ dir: "/usr", name: "file", ext: ".txt" })

HTTP Server (built-in)

const http = require("http");

const server = http.createServer((req, res) => {
  const { method, url, headers } = req;

  if (url === "/health" && method === "GET") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ status: "ok" }));
    return;
  }

  let body = "";
  req.on("data", chunk => (body += chunk));
  req.on("end", () => {
    const parsed = JSON.parse(body || "{}");
    res.writeHead(200);
    res.end("Received");
  });
});

server.listen(3000, () => console.log("Listening on :3000"));

Express.js

const express = require("express");
const app = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));

// Routes
app.get("/users", async (req, res) => {
  const { page = 1, limit = 10 } = req.query;
  const users = await User.find().skip((page-1)*limit).limit(limit);
  res.json(users);
});

app.get("/users/:id", async (req, res) => {
  const user = await User.findById(req.params.id);
  if (!user) return res.status(404).json({ error: "Not found" });
  res.json(user);
});

app.post("/users", async (req, res) => {
  const user = new User(req.body);
  await user.save();
  res.status(201).json(user);
});

app.put("/users/:id", async (req, res) => {
  const user = await User.findByIdAndUpdate(
    req.params.id, req.body, { new: true }
  );
  res.json(user);
});

app.delete("/users/:id", async (req, res) => {
  await User.findByIdAndDelete(req.params.id);
  res.status(204).end();
});

// Error handler (4 params)
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: err.message });
});

// Router
const router = express.Router();
router.get("/", handler);
app.use("/api/v1/users", router);

app.listen(3000);

Events & Streams

const EventEmitter = require("events");

class MyEmitter extends EventEmitter {}
const em = new MyEmitter();

em.on("data", (payload) => console.log("data:", payload));
em.once("connect", () => console.log("connected once"));
em.emit("data", { value: 42 });
em.off("data", handler);
em.removeAllListeners("data");

// Streams
const { Transform, pipeline } = require("stream");
const { promisify } = require("util");
const pipelineAsync = promisify(pipeline);

// Read file as stream
const readable = fs.createReadStream("big.txt", { encoding: "utf8" });
const writable = fs.createWriteStream("out.txt");
await pipelineAsync(readable, writable);

// Transform stream
const upper = new Transform({
  transform(chunk, encoding, callback) {
    callback(null, chunk.toString().toUpperCase());
  }
});
await pipelineAsync(readable, upper, writable);

Environment & Config

// .env (with dotenv)
require("dotenv").config();

const DB_URL  = process.env.DATABASE_URL;
const PORT    = parseInt(process.env.PORT ?? "3000", 10);
const IS_PROD = process.env.NODE_ENV === "production";

const config = {
  port: parseInt(process.env.PORT ?? "3000", 10),
  db:   process.env.DATABASE_URL ?? "mongodb://localhost/dev",
  jwt:  process.env.JWT_SECRET   ?? "dev-secret",
};

Useful Patterns

// Graceful shutdown
process.on("SIGTERM", async () => {
  await server.close();
  await db.disconnect();
  process.exit(0);
});

// Unhandled rejections
process.on("unhandledRejection", (reason) => {
  console.error("Unhandled:", reason);
  process.exit(1);
});

// JWT auth middleware
const jwt = require("jsonwebtoken");
function auth(req, res, next) {
  const token = req.headers.authorization?.split(" ")[1];
  if (!token) return res.status(401).json({ error: "No token" });
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: "Invalid token" });
  }
}

// Child process (exec)
const { exec } = require("child_process");
const { promisify } = require("util");
const execAsync = promisify(exec);
const { stdout } = await execAsync("ls -la");

Found this helpful? Share it!

Tweet LinkedIn WhatsApp
Translate Page