| |

Node.js 85 ๐ŸŸข Cheatsheet

โฑ๏ธ Estimated read: 5 min | |

CLI & Runtime Flags

FlagPurpose
node file.jsRun a script
node -e "code"Evaluate inline code
node --watch file.jsAuto-restart on change
node --env-file=.env app.jsLoad env file natively
node --inspect app.jsStart inspector on :9229
node --inspect-brk app.jsBreak on first line
node --prof app.jsGenerate V8 CPU profile
node --prof-process isolate-*.logRead the profile
node --trace-opt app.jsLog optimized functions
node --trace-deopt app.jsLog deoptimized functions
node --allow-fs-read=/pathRestrict fs reads
node --allow-fs-write=/pathRestrict fs writes
node --allow-net=hostRestrict network
node --experimental-permissionEnable permission model
node --max-old-space-size=4096Heap size (MB)
node --version / -vPrint version

npm Commands

CommandPurpose
npm init -yCreate package.json
npm install pkgInstall dependency
npm install -D pkgInstall dev dependency
npm install -g pkgGlobal install
npm ciClean install from lock file
npm run <script>Run script
npm updateUpdate packages
npm outdatedList outdated packages
npm list --depth=0Top-level deps
npm audit / npm audit fixSecurity check
npx pkgRun without install
npm linkSymlink local package

Built-in Modules

ModuleKey Exports
node:fsreadFile, writeFile, readdir, stat
node:fs/promisesSame, promise-based
node:pathjoin, resolve, basename, dirname, extname
node:httpcreateServer, request, get
node:httpscreateServer, request, get
node:urlURL, URLSearchParams, fileURLToPath
node:osplatform, cpus, homedir, tmpdir, EOL
node:cryptorandomUUID, createHash, createHmac, randomBytes
node:eventsEventEmitter, once, on
node:streamReadable, Writable, Transform, pipeline
node:child_processspawn, exec, execFile, fork
node:worker_threadsWorker, parentPort, MessageChannel
node:utilpromisify, parseArgs, inspect, format
node:bufferBuffer, atob, btoa
node:timers/promisessetTimeout, setInterval, setImmediate
node:assertstrict, equal, deepEqual, throws

Module Systems

FeatureCommonJSESM
Importrequire('x')import x from 'x'
Namedconst { a } = require('x')import { a } from 'x'
Exportmodule.exports = {...}export {...}
Extension.js / .cjs.mjs / type: module
Top-level awaitโŒโœ…
__dirnameโœ… built-inVia import.meta.url
require in fileโœ…createRequire
import()โœ… dynamicโœ… dynamic
// __dirname in ESM
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
const __dirname = dirname(fileURLToPath(import.meta.url));

Event Loop Order

nextTick โ†’ Promise microtasks โ†’ timers โ†’ I/O poll โ†’ setImmediate โ†’ close
FunctionPhasePriority
process.nextTick()Before loop continuesHighest
Promise.then()Microtask queueHigh
setTimeout(fn, 0)Timer phaseMedium
setImmediate(fn)Check phaseMedium
setInterval(fn, ms)Timer phaseMedium

fs Cheatsheet

import fs from 'node:fs';
import fsp from 'node:fs/promises';

// Sync (blocking)
fs.readFileSync('f.txt', 'utf8');
fs.writeFileSync('f.txt', 'data');
fs.existsSync('f.txt');

// Callback
fs.readFile('f.txt', 'utf8', (err, data) => {});

// Promise
await fsp.readFile('f.txt', 'utf8');
await fsp.writeFile('f.txt', 'data');
await fsp.readdir('.');
await fsp.mkdir('dir', { recursive: true });
await fsp.rm('dir', { recursive: true, force: true });

HTTP Server

import { createServer } from 'node:http';

createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ ok: true }));
}).listen(3000);

Child Process

MethodUse
spawn(cmd, args)Streaming, long-running
exec(cmd, cb)Buffered shell command
execFile(file, args)Buffered, no shell
execSync(cmd)Blocking, avoid in servers
fork(module)Spawn Node.js child with IPC
import { spawn } from 'node:child_process';
spawn('ls', ['-la']).stdout.on('data', d => console.log(d.toString()));

process Object

PropertyPurpose
process.envEnvironment variables
process.argvCLI args ([node, script, ...args])
process.cwd()Working directory
process.exit(code)Exit with code
process.pidProcess ID
process.platformOS (linux, darwin, win32)
process.versionNode version
process.memoryUsage()Heap stats
process.uptime()Seconds since start
process.on('SIGINT', () => { process.exit(0); });
process.on('uncaughtException', (e) => console.error(e));
process.on('unhandledRejection', (e) => console.error(e));

Streams

TypePurpose
ReadableSource (fs.createReadStream)
WritableDestination (fs.createWriteStream)
DuplexBoth (TCP socket)
TransformModify (zlib.createGzip)
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';

await pipeline(
  createReadStream('in.txt'),
  createGzip(),
  createWriteStream('in.txt.gz')
);

Events

import { EventEmitter } from 'node:events';
const bus = new EventEmitter();
bus.on('event', fn);
bus.once('event', fn);
bus.emit('event', data);
bus.off('event', fn);

Worker Threads

// main.js
import { Worker } from 'node:worker_threads';
const w = new Worker('./worker.js');
w.on('message', (msg) => console.log(msg));
w.postMessage({ task: 'compute' });

// worker.js
import { parentPort } from 'node:worker_threads';
parentPort.on('message', (msg) => parentPort.postMessage('done'));

Common npm Scripts

{
  "scripts": {
    "start": "node index.js",
    "dev": "node --watch index.js",
    "test": "node --test",
    "build": "tsc",
    "lint": "eslint .",
    "format": "prettier --write ."
  }
}

package.json Fields

FieldPurpose
namePackage name
versionSemVer version
mainCJS entry point
moduleESM entry point
exportsConditional exports
type"module" for ESM
binCLI executables
enginesNode version range
scriptsNamed tasks
dependenciesRuntime deps
devDependenciesDev-only deps

Environment Variables

process.env.PORT ?? '3000';
process.env.NODE_ENV === 'production';

// Load .env
node --env-file=.env app.js;

Error Handling

// Try/catch with await
try { await fsp.readFile('f'); } catch (e) { console.error(e); }

// Unhandled rejections
process.on('unhandledRejection', console.error);

// HTTP errors
class NotFoundError extends Error { status = 404; }

Debugging

ToolUse
node --inspectChrome DevTools / VS Code
node --inspect-brkBreak on first line
console.logQuick debugging
node:util.inspect(obj, { depth: null })Deep print
--trace-warningsShow warning stack traces

Performance Flags

FlagPurpose
--profV8 CPU profile
--prof-processRead profile
--trace-optLog optimization
--trace-deoptLog deoptimization
--max-old-space-size=4096Heap limit
--max-semi-space-size=64Young gen size

Cluster

import cluster from 'node:cluster';
import { cpus } from 'node:os';

if (cluster.isPrimary) {
  for (let i = 0; i < cpus().length; i++) cluster.fork();
} else {
  // worker: start server
  server.listen(3000);
}

Quick Tips

DoDon’t
Use node: prefixRely on implicit core imports
Use fs/promises in asyncBlock loop with sync fs
Use pipeline for streamsPipe manually (leaks)
Use --watch in devRestart manually
Use worker_threads for CPUBlock event loop
Use --env-fileHardcode secrets
Use node --testAssume no test runner

Status of Common Tasks

TaskPackage
HTTP frameworkExpress, Fastify, Hono
Env varsnative --env-file, dotenv
Testingnative --test, vitest, jest
Lintingeslint
Loggingpino, winston
Configconvict, zod-validated env
Validationzod, joi

Node.js โ€” cheatsheet, not a chapter: flags, modules, event loop order, snippets, and the one-liners you actually reach for.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!