Back to roadmaps nodejs Course

Node.js Cheat Sheet

This quick reference guide provides code snippets for the most common APIs in the Node.js runtime ecosystem.


1. File System (fs/promises)

import fs from "fs/promises";

// Read file as string
const text = await fs.readFile("file.txt", "utf8");

// Write file
await fs.writeFile("file.txt", "Hello World", "utf8");

// Append file
await fs.appendFile("file.txt", "New line\n", "utf8");

// Check stats (size, type)
const stats = await fs.stat("file.txt");
const isFile = stats.isFile();

// List directory items
const files = await fs.readdir("src");

2. Path Resolution (path)

import path from "path";

// Join segments (cross-platform)
const fullPath = path.join("src", "controllers", "user.js");

// Resolve absolute path
const absolute = path.resolve("src", "index.js");

// Get file extension
const ext = path.extname("app.config.json"); // Outputs: .json

// Parse path info
const info = path.parse("/var/log/app.log");
// info: { root: '/', dir: '/var/log', base: 'app.log', ext: '.log', name: 'app' }

3. Asynchronous Events (events)

import { EventEmitter } from "events";

const myEmitter = new EventEmitter();

// Setup listener
myEmitter.on("update", (status) => {
  console.log("Status:", status);
});

// Emit event
myEmitter.emit("update", "running");

4. Hardware and Platform Metrics (os)

import os from "os";

const cpus = os.cpus().length; // CPU count
const freeMem = os.freemem(); // Free RAM bytes
const totalMem = os.totalmem(); // Total RAM bytes
const home = os.homedir(); // Home directory path
const platform = os.platform(); // darwin, win32, linux

5. Streams Piping (stream/promises)

import fs from "fs";
import zlib from "zlib";
import { pipeline } from "stream/promises";

// Safe piping with automatic error cleanup
await pipeline(
  fs.createReadStream("app.log"),
  zlib.createGzip(),
  fs.createWriteStream("app.log.gz")
);
Published on Last updated: