Skip to main content
Backend & APIs

Node.js Runtime & Native APIs

Essential

Native Node.js CLI flags (--watch), fs/promises, streams, path modules, worker threads, and event emitters.

Instant Copy & SearchProduction Flagged SyntaxCurrent Flag Reference

Node.js Runtime & Native APIs Interactive Command Directory

Browse, search, and copy battle-tested commands & syntax recipes (16 Total Commands).

16+ Verified Recipes
Watch Mode CLI--watch, --env-file
node --watch --env-file=.env server.js

Run script with native file watcher and automatic .env environment loading (Node 20+).

File System Promisesnode:fs/promises
import fs from 'node:fs/promises'; const data = JSON.parse(await fs.readFile('data.json', 'utf-8')); await fs.writeFile('output.json', JSON.stringify(data, null, 2));

Read and write files asynchronously using native node:fs/promises.

Path Resolutionnode:path
import path from 'node:path'; const absPath = path.join(process.cwd(), 'uploads', filename);

Safely resolve cross-platform filesystem paths.

Streams Pipelinestream/promises
import { pipeline } from 'node:stream/promises'; import { createReadStream, createWriteStream } from 'node:fs'; import zlib from 'node:zlib'; await pipeline( createReadStream('input.txt'), zlib.createGzip(), createWriteStream('input.txt.gz') );

Stream data with backpressure management and memory efficiency.

Worker Threadsnode:worker_threads
import { Worker } from 'node:worker_threads'; const worker = new Worker('./worker.js', { workerData: { task: 42 } });

Offload CPU-intensive operations to dedicated parallel worker thread.

Multi-Core Clusteringnode:cluster
import cluster from 'node:cluster'; import http from 'node:http'; import { availableParallelism } from 'node:os'; if (cluster.isPrimary) { for (let i = 0; i < availableParallelism(); i++) cluster.fork(); } else { http.createServer((req, res) => res.end('OK')).listen(8000); }

Distribute HTTP server workloads across all CPU cores using native cluster IPC fork model.

Request CancellationAbortController, signal
const ac = new AbortController(); const timeoutId = setTimeout(() => ac.abort(), 5000); try { const res = await fetch('https://api.internal/data', { signal: ac.signal }); } finally { clearTimeout(timeoutId); }

Enforce deterministic timeout cancellation on native fetch and child processes with AbortController.

Async Event Iterationevents.on
import { EventEmitter, on } from 'node:events'; const ee = new EventEmitter(); for await (const [event] of on(ee, 'data')) { console.log('Received event:', event); }

Consume EventEmitter event streams sequentially using standard for-await-of async iteration.

Remote Debugging--inspect
node --inspect=0.0.0.0:9229 server.js

Attach Chrome DevTools or VS Code debugger over WebSocket inspector port.

Heap Memory Allocation--max-old-space-size
node --max-old-space-size=4096 server.js

Raise V8 engine Old Generation heap memory limit to 4GB for memory-intensive data tasks.

Streaming Pipelinesstream/promises
import { createGzip } from 'node:zlib'; import { createReadStream, createWriteStream } from 'node:fs'; import { pipeline } from 'node:stream/promises'; await pipeline(createReadStream('input.txt'), createGzip(), createWriteStream('input.txt.gz'));

Safely pipe streams with automated backpressure handling and resource destruction.

Cryptography & HMACcrypto.createHmac
import crypto from 'node:crypto'; const hash = crypto.createHmac('sha256', secret).update(payload).digest('hex');

Generate SHA256 HMAC cryptographic signature for secure webhook payload validation.

Crash PreventionunhandledRejection
process.on('unhandledRejection', (reason, promise) => { console.error('Unhandled Rejection at:', promise, 'reason:', reason); process.exit(1); });

Capture unhandled Promise rejections globally to log stack trace and perform clean shutdown.

Async Context TrackingAsyncLocalStorage
import { AsyncLocalStorage } from 'node:async_hooks'; const asyncLocalStorage = new AsyncLocalStorage(); asyncLocalStorage.run({ traceId: 'abc-123' }, () => { const store = asyncLocalStorage.getStore(); });

Propagate request IDs and tracing metadata across asynchronous execution call chains without parameter passing.

CPU Profiling--prof, --prof-process
node --prof app.js && node --prof-process isolate-*.log > processed.txt

Collect V8 engine low-level tick sampling profiling data and convert to human-readable format.

Binary BuffersBuffer.alloc
const buffer = Buffer.alloc(1024); buffer.writeUInt32BE(0x12345678, 0);

Allocate and manipulate fixed-length raw memory buffers with big-endian integer encoding.

Zero Setup100% In-Browser Execution

Companion Developer Tools & Playgrounds

Accelerate command execution and syntax debugging with HelloAIHub suite of interactive tools.

Explore all developer tools

Node.js Runtime & Native APIs: Command Groups & Quick Index

16 indexed entries across 16 sections
Watch Mode CLI1 items
File System Promises1 items
Path Resolution1 items
Streams Pipeline1 items
Worker Threads1 items
Multi-Core Clustering1 items
Request Cancellation1 items
Async Event Iteration1 items
Remote Debugging1 items
Heap Memory Allocation1 items
Streaming Pipelines1 items
Cryptography & HMAC1 items
Crash Prevention1 items
Async Context Tracking1 items
CPU Profiling1 items
Binary Buffers1 items

Highlighted Flags & Syntax Examples in Node.js Runtime & Native APIs

node --watch --env-file=.env server.js

Run script with native file watcher and automatic .env environment loading (Node 20+).

Flags: --watch, --env-file
import fs from 'node:fs/promises'; const data = JSON.parse(await fs.readFile('data.json', 'utf-8')); await fs.writeFile('output.json', JSON.stringify(data, null, 2));

Read and write files asynchronously using native node:fs/promises.

Flags: node:fs/promises
import path from 'node:path'; const absPath = path.join(process.cwd(), 'uploads', filename);

Safely resolve cross-platform filesystem paths.

Flags: node:path
import { pipeline } from 'node:stream/promises'; import { createReadStream, createWriteStream } from 'node:fs'; import zlib from 'node:zlib'; await pipeline( createReadStream('input.txt'), zlib.createGzip(), createWriteStream('input.txt.gz') );

Stream data with backpressure management and memory efficiency.

Flags: stream/promises

Frequently Asked Questions

Expert recommendations, common traps, and production best practices for Node.js Runtime & Native APIs.

What is the difference between CommonJS and ES Modules in Node.js?

CommonJS (require/module.exports) loads modules synchronously at runtime. ES Modules (import/export) are parsed statically before execution, support top-level await, and are the modern standard across JavaScript runtimes.

Why is streaming critical when handling large files in Node.js?

Reading a 2GB file with fs.readFile attempts to buffer the entire 2GB into V8 heap memory at once, often crashing with 'JavaScript heap out of memory'. Streams process data in small chunks (typically 64KB), using constant low memory.

How does the Node.js event loop work (microtasks vs timers vs I/O polling vs check phase)?

The event loop processes phases in sequence: Timers (setTimeout/setInterval) -> Pending I/O callbacks -> Idle/Prepare -> Poll (retrieves new I/O events) -> Check (setImmediate) -> Close callbacks. Crucially, the Microtask Queue (process.nextTick and Promise callbacks) drains completely between every single task in each phase.

What is the difference between Worker Threads and the Cluster module?

The Cluster module spawns multiple isolated OS processes sharing server ports; memory is not shared, making it ideal for scaling HTTP servers across CPU cores. Worker Threads ('node:worker_threads') run multiple threads inside a single OS process sharing memory (via SharedArrayBuffer), making it ideal for heavy in-memory computation like encryption or image processing.

What is backpressure in Node.js streams and why does pipeline() prevent out-of-memory crashes?

Backpressure occurs when a stream reader/producer generates data faster than a writable stream/consumer can write it to disk or network. Raw stream.pipe() ignores write buffer saturation, accumulating unwritten chunks in RAM until the process crashes. stream/promises.pipeline() respects pause/drain signals and guarantees proper cleanup.

What is the difference between CommonJS (require) and ES Modules (import) in modern Node.js?

CommonJS (CJS) is synchronous and evaluated at runtime, making dynamic requires possible. ES Modules (ESM) are asynchronous and statically analyzed before execution, enabling top-level await and tree-shaking. Node.js natively supports ESM when 'type': 'module' is specified in package.json.

Cross-Hub Skill Acceleration

Combine command lookups with active coding interviews and complete career paths.

Need More Cheat Sheets?

Explore developer cheat sheets and syntax guides on HelloAIHub.

Browse All Cheat Sheets