Node.js Cheatsheet

Basics

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.

Running Node.js

// Run a file
node app.js

// Run with watch mode (Node 18+)
node --watch app.js

// Execute inline
node -e "console.log(process.version)"

// REPL
node
FlagEffect
--watchRestart on file change (Node 18+)
--inspectOpen V8 debugger (port 9229)
--inspect-brkBreak on first line, then wait for debugger
--env-file=.envLoad env file (Node 20.6+)
--max-old-space-size=4096Set heap limit in MB
-r moduleRequire CJS module before script runs
--import modulePreload ESM before script runs; register hooks via module.register() (replaces deprecated --loader)

Console Methods

console.log("hello", { x: 1 });        // stdout
console.error("oops");                  // stderr
console.warn("watch out");             // stderr
console.info("info");                  // alias for log

console.dir(obj, { depth: null });     // full object tree
console.table([{ a: 1 }, { a: 2 }]);  // tabular output
console.time("label");
// ... code ...
console.timeEnd("label");              // label: 12.345ms

console.count("hit");                  // hit: 1
console.countReset("hit");

console.group("group");
console.log("indented");
console.groupEnd();

console.assert(1 === 2, "fail msg");   // prints only if falsy
console.trace("where am I");          // stack trace to stdout

Global Objects

globalThis          // the universal global (replaces global/window/self)
global              // Node global object
__filename          // /abs/path/to/current/file  (CommonJS only)
__dirname           // /abs/path/to/current/dir   (CommonJS only)

// ESM equivalents
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname  = dirname(__filename);

import.meta.url    // file:///abs/path/to/file.js  (ESM)
import.meta.dirname  // Node 21.2+ — absolute dir without the helper above
import.meta.filename // Node 21.2+

Timers

// One-shot
const t = setTimeout(() => console.log("later"), 1000);
clearTimeout(t);

// Repeating
const i = setInterval(() => console.log("tick"), 500);
clearInterval(i);

// Next iteration of the event loop
setImmediate(() => console.log("immediate"));
clearImmediate(handle);

// Microtask — runs before any I/O or timers
queueMicrotask(() => console.log("microtask"));

// Promise-based timers
import { setTimeout as sleep, setInterval as tick } from "node:timers/promises";

await sleep(1000);                         // resolves after 1 s
await sleep(1000, "value");               // resolves with "value"
for await (const _ of tick(500)) { ... } // async iterable interval

Timer Execution Order

setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
Promise.resolve().then(() => console.log("promise"));
queueMicrotask(() => console.log("microtask"));
process.nextTick(() => console.log("nextTick"));

// Output order (inside I/O callback the timeout/immediate order can swap):
// nextTick → promise → microtask → timeout → immediate
// (promise before microtask: both are microtasks, FIFO by registration)

process.nextTick runs before any other microtask. Prefer queueMicrotask for user code. Caveat: that order holds in CommonJS; at ESM top level (.mjs) module evaluation itself runs in a microtask, so already-queued promise/microtask callbacks fire before nextTick (promise → microtask → nextTick).

Error Handling Basics

// Synchronous
try {
  JSON.parse("bad");
} catch (err) {
  console.error(err.message);  // Unexpected token...
} finally {
  // always runs
}

// Async / Promise
async function main() {
  try {
    await fs.promises.readFile("nope.txt");
  } catch (err) {
    if (err.code === "ENOENT") console.error("File not found");
    else throw err;
  }
}

// Unhandled rejections (catch-all, last resort)
process.on("unhandledRejection", (reason, promise) => {
  console.error("Unhandled rejection:", reason);
  process.exit(1);
});

// Uncaught exceptions
process.on("uncaughtException", (err) => {
  console.error("Uncaught:", err);
  process.exit(1);
});

Common Error Codes

CodeMeaning
ENOENTFile or directory not found
EACCESPermission denied
EADDRINUSEPort already in use
ECONNREFUSEDConnection refused
EEXISTFile already exists
EISDIRExpected file, got directory
EMFILEToo many open file descriptors
EPERMOperation not permitted

REPL Tips

// Inside REPL:
.help        // list commands
.break       // exit multi-line input
.clear       // reset context
.editor      // multi-line edit mode (Ctrl+D to run)
.save file   // save session to file
.load file   // load a file into session
_            // last evaluated value