โฑ๏ธ Estimated read: 5 min
|
๐จ๏ธ Print / PDF
|
๐ Copy Link
CLI & Runtime Flags
Flag Purpose 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
Command Purpose 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
Module Key Exports node:fsreadFile, writeFile, readdir, statnode:fs/promisesSame, promise-based node:pathjoin, resolve, basename, dirname, extnamenode:httpcreateServer, request, getnode:httpscreateServer, request, getnode:urlURL, URLSearchParams, fileURLToPathnode:osplatform, cpus, homedir, tmpdir, EOLnode:cryptorandomUUID, createHash, createHmac, randomBytesnode:eventsEventEmitter, once, onnode:streamReadable, Writable, Transform, pipelinenode:child_processspawn, exec, execFile, forknode:worker_threadsWorker, parentPort, MessageChannelnode:utilpromisify, parseArgs, inspect, formatnode:bufferBuffer, atob, btoanode:timers/promisessetTimeout, setInterval, setImmediatenode:assertstrict, equal, deepEqual, throws
Module Systems
Feature CommonJS ESM Import require('x')import x from 'x'Named const { a } = require('x')import { a } from 'x'Export module.exports = {...}export {...}Extension .js / .cjs.mjs / type: moduleTop-level await โ โ
__dirnameโ
built-in Via import.meta.url require in fileโ
createRequireimport()โ
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
Function Phase Priority process.nextTick()Before loop continues Highest Promise.then()Microtask queue High setTimeout(fn, 0)Timer phase Medium setImmediate(fn)Check phase Medium setInterval(fn, ms)Timer phase Medium
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
Method Use 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
Property Purpose 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
Type Purpose 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
Field Purpose namePackage name versionSemVer version mainCJS entry point moduleESM entry point exportsConditional exports type"module" for ESMbinCLI 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
Tool Use 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
Flag Purpose --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
Do Don’t Use node: prefix Rely on implicit core imports Use fs/promises in async Block loop with sync fs Use pipeline for streams Pipe manually (leaks) Use --watch in dev Restart manually Use worker_threads for CPU Block event loop Use --env-file Hardcode secrets Use node --test Assume no test runner
Status of Common Tasks
Task Package HTTP framework Express, Fastify, Hono Env vars native --env-file, dotenv Testing native --test, vitest, jest Linting eslint Logging pino, winston Config convict, zod-validated env Validation zod, joi
Node.js โ cheatsheet, not a chapter: flags, modules, event loop order, snippets, and the one-liners you actually reach for.
โ Previous Node.js 84 ๐ข Native C++ Addons and High-Performance Native API (Node-API / N-API)
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!