Node.js Cheatsheet

Path and OS

Use this Node.js reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

path — Core Methods

import path from "node:path";
// or: const path = require("node:path");
MethodExampleResult
path.join(...parts)path.join("a", "b", "c.js")"a/b/c.js"
path.resolve(...parts)path.resolve("src", "index.js")"/cwd/src/index.js"
path.basename(p)path.basename("/a/b/c.js")"c.js"
path.basename(p, ext)path.basename("/a/b/c.js", ".js")"c"
path.dirname(p)path.dirname("/a/b/c.js")"/a/b"
path.extname(p)path.extname("c.tar.gz")".gz"
path.normalize(p)path.normalize("a//b/../c")"a/c"
path.relative(from, to)path.relative("/a/b", "/a/c/d")"../c/d"
path.isAbsolute(p)path.isAbsolute("/etc")true
path.parse(p)path.parse("/a/b/c.js"){ root, dir, base, ext, name }
path.format(obj)path.format({ dir:"/a", name:"c", ext:".js" })"/a/c.js"

path.join vs path.resolve

// join — concatenates segments with the platform separator
path.join("/foo", "bar", "baz.js");  // "/foo/bar/baz.js"
path.join("foo",  "../bar");          // "bar"
path.join("", "file.js");            // "file.js"  (relative)

// resolve — builds an ABSOLUTE path, processes from RIGHT to LEFT
path.resolve("foo", "bar");          // "/cwd/foo/bar"
path.resolve("/a", "b", "/c");       // "/c"  (absolute segment resets)
path.resolve(__dirname, "src/app");  // absolute from current file's dir

path.parse and path.format

path.parse("/home/user/file.tar.gz");
// {
//   root: "/",
//   dir:  "/home/user",
//   base: "file.tar.gz",
//   ext:  ".gz",
//   name: "file.tar"
// }

path.format({ dir: "/home/user", name: "file", ext: ".txt" });
// "/home/user/file.txt"
// Note: base overrides name+ext if both provided

Platform Separators

path.sep;       // "/"  (Linux/macOS) | "\\"  (Windows)
path.delimiter; // ":"  (Linux/macOS) | ";"   (Windows)

// Force POSIX paths on any platform
import { posix, win32 } from "node:path";
posix.join("a", "b");    // "a/b"
win32.join("a", "b");    // "a\\b"

// Convert Windows paths ↔ POSIX
"C:\\Users\\foo".split(path.win32.sep).join(path.posix.sep);

os — System Information

import os from "node:os";
// or: const os = require("node:os");
Method / PropertyReturns
os.platform()"linux" "darwin" "win32" "freebsd"
os.arch()"x64" "arm64" "ia32"
os.release()Kernel version string
os.version()OS version string (Node 13.11+)
os.type()"Linux" "Darwin" "Windows_NT"
os.homedir()/home/user
os.tmpdir()/tmp
os.hostname()Machine hostname
os.uptime()Seconds since boot
os.totalmem()Total RAM in bytes
os.freemem()Free RAM in bytes
os.cpus()Array of CPU core info objects
os.networkInterfaces()Object of network interface arrays
os.userInfo(){ username, uid, gid, shell, homedir }
os.loadavg()[1min, 5min, 15min] load averages (Unix)
os.EOL"\n" (Unix) or "\r\n" (Windows)
os.devNull"/dev/null" or "\\.\nul"

os.cpus()

const cpus = os.cpus();
// [{ model, speed (MHz), times: { user, nice, sys, idle, irq } }, ...]

console.log(`${cpus.length} cores — ${cpus[0].model}`);

// Rough CPU usage % for a core
const t = cpus[0].times;
const total = Object.values(t).reduce((a, b) => a + b, 0);
const usage = ((total - t.idle) / total * 100).toFixed(1);

os.networkInterfaces()

const ifaces = os.networkInterfaces();
for (const [name, addrs] of Object.entries(ifaces)) {
  for (const addr of addrs) {
    if (addr.family === "IPv4" && !addr.internal) {
      console.log(`${name}: ${addr.address}`);
    }
  }
}
// addr: { address, netmask, family, mac, internal, cidr, scopeid }

Common Patterns

// Cross-platform path from home dir
const configDir = path.join(os.homedir(), ".config", "myapp");

// Temp file path
const tmpFile = path.join(os.tmpdir(), `work-${Date.now()}.tmp`);

// Detect platform
const isWindows = os.platform() === "win32";
const isMac     = os.platform() === "darwin";

// Available memory in GB
const freeMB = (os.freemem() / 1024 ** 2).toFixed(0);

// Worker count heuristic
const workerCount = Math.max(1, os.cpus().length - 1);