Skills covering Node.js features added since v24, plus removals and changed defaults.

GitHub stars
6

Install

/plugin install node-skills@node-skills

Run it inside Claude Code after adding the marketplace with /plugin marketplace add jasnell/node-skills.

Contents

Discovered from source

Skills 18

node:bench

FeatureVersionsStabilityFlag
node:bench (bench, suite, describe, hooks, createRunner, run, runFile), node:bench/reportersv26.9.0 (not on v24)1.0 Early development--experimental-bench
--bench and --bench-* flags (except --bench-gc)v26.9.01 Experimental--experimental-bench
doNotOptimize, --bench-gc, the gc option, end() defaulting to 1 op, the bench:environment recordadded: REPLACEME (main only; absent in v26.13.0)1.0--experimental-bench

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

A benchmark file

// parse.bench.mjs: declare only, never call run() (the CLI rejects it)
import { bench, suite } from 'node:bench';
suite('JSON', () => {
  const input = JSON.stringify({ a: [1, 2, 3] });
  bench('parse', { samples: 30, warmup: 10 }, (b) => {
    const ops = 10_000; let n = 0;
    b.start();
    for (let i = 0; i < ops; i++) n += JSON.parse(input).a.length;
    b.end(ops);                       // always pass operations (required on v26.13)
    if (n !== 3 * ops) throw new Error('wrong result'); // keep the work observable
  });
});
node --experimental-bench --bench 'bench/**/*.bench.mjs'   # one child process per file
node --experimental-bench --bench --bench-reporter=json --bench-samples=50 x.bench.mjs > out.ndjson

Results in code

import { createRunner } from 'node:bench';
const r = createRunner();             // runs only on r.run(), once
r.bench('x', { samples: 20 }, (b) => { b.start(); work(); b.end(1); });
for await (const { type, data } of r.run())
  if (type === 'bench:complete' && !data.error) use(data.samples, data.summary);

Each sample is { operations, duration_ns: bigint, rate /* ops/s */ }. summary.mean is the mean of per-sample rates, not pooled throughput. To ask "is B faster than A", record integer ns or ps per op into a Histogram and use welchTest/mannWhitneyTest. See the node-histogram-stats skill.

Pitfalls

  • Each warmup and each sample calls fn once with a new context, and fn must call start()+end() or record() exactly once. beforeEach runs once per benchmark, not per sample.
  • A loop whose result is unused can be eliminated. The spec reporter flags ≥ 1 op/ns as implausible. Validate an aggregate, or use doNotOptimize(v) on main.
  • A failure in a module-level run sets process.exitCode = 1. createRunner() runs don't.
  • gc: 'once' | 'sample' needs --expose-gc. --bench-gc adds it to children automatically, except with --bench-isolation=none. On v26.13 gc is silently ignored.
  • --bench can't be combined with --test, --watch, --eval or --check.

Don't

  • Don't hand-roll Date.now()/performance.now() loops: they have no warmup or per-sample stats.
  • Don't add benchmark.js, tinybench, mitata or cronometro when Node ≥ 26.9 is available. Use node:bench.
  • Don't treat a confidence interval as pass/fail. Keep the raw samples.

Reference

  • rules/api.md — read for every option, BenchContext method, hook, and event/result field.
  • rules/cli.md — read for flags, isolation modes, reporters (spec/json/custom), and runFile.
  • rules/measurement.md — read for warmup, GC modes, dead-code elimination, variable batches, and comparing runs.

Node.js crypto (v24+)

Task → featureVersionsStabilityFlag
Hash a password → argon2/argon2Syncv24.7.02
Post-quantum key exchange → 'ml-kem-768' + encapsulatev24.7.02
PQ signatures → 'ml-dsa-65'; 'slh-dsa-*'v24.6.0; v24.8.02
WebCrypto ML-KEM/ML-DSA/Argon2/KMAC/SHA3/cSHAKE/OCB/ChaCha20, getPublicKey, supportsv24.7.0, v24.8.01.1
WebCrypto hybrid KEM MLKEM768-X25519v26.10.0, v24.22.01.1
WebCrypto TurboSHAKE, KT128v25.9.0, v24.18.01.1
createMac/getMacsv26.9.0, v24.22.01.2
AES-SIV, AES-GCM-SIVv26.8.0, v24.22.02
Time-ordered ids → randomUUIDv7()v26.1.0, v24.16.02
.p12 → parsePKCS12v26.10.0, v24.22.02
Self-signed cert for tests → generateX509CertificateSync, new x509.* gettersv27.0.0 (not v24/v26)1.2
'raw-public'/'raw-private'/'raw-seed' formatsv24.15.02
createPrivateKey(new URL(…)) (OpenSSL STORE)v26.7.0, v24.21.01.1--allow-openssl-store
crypto.fips.indicator channelv26.9.0, v24.22.01--enable-fips-indicator-events

PQC needs OpenSSL 3.5+, Argon2 3.2+: check process.versions.openssl.

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Hash a password

const p = { message: pw, nonce: randomBytes(16), parallelism: 1, tagLength: 32, memory: 19456, passes: 2 }; // KiB
const tag = await promisify(argon2)('argon2id', p); // raw bytes: store nonce+params; verify with timingSafeEqual

Post-quantum

const { publicKey, privateKey } = generateKeyPairSync('ml-kem-768');
const { sharedKey, ciphertext } = encapsulate(publicKey); // decapsulate(privateKey, ciphertext) -> sharedKey
const sig = sign(null, data, { key: mlDsaKey, context }); // algorithm must be null

Test certificate (v27+)

const cert = generateX509CertificateSync({ subject: [{ name: 'CN', value: 'localhost' }], publicKey,
  serialNumber: 1n, notBefore, notAfter, signature: { key: privateKey, digest: 'sha256' },
  extensions: [{ type: 'subjectAltName', names: [{ type: 'dns', value: 'localhost' }] }] });
// cert.toString() is PEM; no implicit extensions

Pitfalls

  • SHAKE needs outputLength (bytes): v27+ throws, v25/v26 warn (DEP0198). WebCrypto XOFs need { name, outputLength } in bits.
  • SubtleCrypto.supports() validates full params: ('encrypt', 'AES-OCB') is false (no iv).
  • v27+ rejects CryptoKey in node:crypto: use KeyObject.from() (extractable keys only).
  • Short GCM tags need authTagLength on the decipher (v26+). setEngine is gone in v27.

Don't

bcrypt/argon2 npm; uuid for v7; selfsigned/node-forge/openssl req for test certs (v27+); node-forge for .p12; js-sha3 for SHA-3/KMAC; @noble/post-quantum.

Reference

Node.js diagnostics (v24+)

FeatureVersionsStabilityFlag
TracingChannelv19.9.0, v18.19.0 (Stable in v26.8.0)2—
boundedChannel, channel.withStoreScopev26.1.0 (not v24)1—
als.withScope / RunScopev25.9.0, v24.20.01—
AsyncLocalStorage({ defaultValue, name })v24.0.02—
v8.startCpuProfile (sync)v25.0.0, v24.12.0——
v8.startHeapProfile (sync)v26.1.0 (not v24)1—
v8.setHeapProfileNearHeapLimitv26.9.0 (not v24)1—
worker.startCpuProfile / .startHeapProfilev24.8.0 / v24.9.0, v22.20.02—
node inspect --probev26.1.0, v24.16.0; JSON v2 + --max-hit v26.4.0, v24.19.0; --cond v26.6.0, v24.20.01—
inspector DOMStorage.*v25.5.0, v24.16.01.1--experimental-storage-inspection
Built-in channelssee rules/diagnostics-channel.md1—

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Instrument a library (APM)

import { tracingChannel } from 'node:diagnostics_channel';
const ch = tracingChannel('mylib.db.query'); // once, at module top level
export function query(sql) {
  if (!ch.hasSubscribers) return run(sql);
  return ch.tracePromise(run, { sql }, null, sql);
}
// APM side: ch.start.bindStore(als, (ctx) => span(ctx)); ch.subscribe({...})

Scoped context with using

{ using _ = als.withScope(store); syncWork(); } // restored on exit/throw
{ using _ = ch.withStoreScope(msg); }          // enter bound stores + publish
{ using _ = bounded.withScope(ctx); }          // tracing:<name>:start ... end

Profile a section

const h = v8.startCpuProfile({ sampleInterval: 1 }); hot();
writeFileSync('x.cpuprofile', h.stop()); // JSON string; `using` discards
// worker.startCpuProfile() is async: await handle.stop()

Logpoint without editing code

node inspect --json --probe src/app.js:42 --expr 'user.id' --cond 'user.admin' --max-hit 5 app.js

Pitfalls

  • A using scope opened in an async function before the first await leaks into the caller; use als.run().
  • boundedChannel.run() sets neither ctx.result nor ctx.error. A bound store makes hasSubscribers true.
  • tracePromise (v26+) returns thenables as-is, non-thenables with a warning; v24 wraps both in a Promise.
  • defaultValue applies only when no store was entered; run(undefined)/exit() give undefined.
  • One heap profile at a time. setHeapProfileNearHeapLimit needs an active startHeapProfile().
  • Before v24.20, --cond is rejected with a misleading "Use --" usage error.
  • v8.queryObjects is documented Stable but still warns ExperimentalWarning.

Don't

  • Don't monkey-patch modules or use async_hooks.createHook for tracing: use channels + bindStore.
  • Don't use enterWith() for block scope (withScope()) or console.log edits to inspect values (--probe).

Reference

Verify experimental Node.js features before relying on them

Experimental APIs (Stability 1, 1.0, 1.1) change between minor releases. Option names change, methods move, and flags get renamed or removed. A skill describes one snapshot. The installed Node.js is the source of truth.

Checklist (do not skip for Stability 1.x)

  1. Find the runtime that will run the code. Run node --version, but also check .nvmrc, package.json engines, volta, the Dockerfile FROM node:<tag>, and the CI node-version. The shell's node may not be the one that matters.
  2. Probe the exact items you will use. Run the bundled script with the target binary:
    node scripts/probe.mjs --flag --experimental-stream-iter --module node:stream/iter
    node scripts/probe.mjs --module node:zlib:ZipFile.openSync --global URLPattern
    node scripts/probe.mjs --flag --experimental-bench --list node:bench   # list exports
    node scripts/probe.mjs --node ./out/Release/node --flag --process-timeout
    
    The probe passes --experimental-*/--allow-* flags through to the module checks and exits 1 if anything is missing. If you can't run the script, use a one-liner instead: node --experimental-x -p "typeof require('node:mod').thing" and node --help | grep -- --flag.
  3. Read the docs for that version, not latest: https://nodejs.org/docs/<version>/api/<module>.html. For a pre-release build, read doc/api/<module>.md in its checkout. Check the YAML added:/changes: history and the Stability line of each API you use.
  4. Prefer behavior over docs. For anything subtle (defaults, units, error codes), run a 5-line script instead of trusting prose.
  5. Gate or fall back. If the code must run on several versions, use feature detection (typeof x === 'function', a try { await import() } block), not a version-string compare. State the minimum version in engines or in a comment.
  6. Tell the user that the code depends on an experimental API, which flag it needs, and that the API may change in minor releases.

Reading added: lists

added: [v26.8.0, v24.22.0] means the feature is in 24.22+ on the v24 line and in 26.8+. It is not in v25.x or in 26.0–26.7. A single entry v26.1.0 means the feature is not on v24 at all.

Pitfalls

  • A flag that the installed version does not accept fails the process with bad option. That means the version lacks the feature, not that the flag is spelled wrong.
  • Some modules only resolve with the node: prefix (node:sqlite, node:test, node:bench) and some only behind a flag. Probe with the flag.
  • Flags that get unflagged keep an opposite --no-experimental-* form. After that, passing the old --experimental-* flag may warn or error.

node:ffi: call native libraries without an addon

FeatureVersionsStabilityFlag
node:ffi (dlopen, DynamicLibrary, memory helpers)v26.1.01none; --no-experimental-ffi disables
--allow-ffi (permission model)v26.1.01.1with --permission
getCurrentEventLoop()v26.6.01none
dlopen of a path inside a mounted node:vfsv26.10.01none
library.toFunction()main only (no YAML; absent in v26.13.0)1none

Not on v24. Present only in builds with FFI support (the official v26 builds have it). Importing it emits an ExperimentalWarning.

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Call a C function

import { dlopen } from 'node:ffi';
{
  using h = dlopen('libc.so.6', {          // Linux glibc; NOT 'libc.so' (linker script)
    strlen: { arguments: ['string'], return: 'uint64' },
    abs:    { arguments: ['int32'],  return: 'int32' },
  });
  h.functions.strlen('héllo');             // 6n: 64-bit returns are always bigint
  h.functions.abs(-5);                     // 5
}                                          // library closed here

dlopen(null, …) resolves from the process image (not on Windows). Build names portably with `libfoo.${ffi.suffix}` (so/dylib/dll).

Pointers and callbacks

const p = malloc(16);                      // 'pointer' returns are bigint
ffi.exportString('hi', p, 16); ffi.toString(p); free(p);
const cmp = lib.registerCallback({ arguments: ['pointer','pointer'], return: 'int32' },
  (a, b) => ffi.getInt32(a) - ffi.getInt32(b));
qsort(int32Array, n, 4, cmp); lib.unregisterCallback(cmp);

Pitfalls

  • No coercion: abs(1.5), abs('5'), abs(5n) and bool true throw ERR_INVALID_ARG_VALUE. Pass 0/1 for bool.
  • A 'string' return is a bigint pointer. Decode it with ffi.toString().
  • Wrong signatures are not detected. Declaring bool for a C int truncates it, and a wrong pointer crashes the process.
  • A callback that throws aborts the process. Callbacks must be sync and run on the creating thread. A 'function' argument needs a registerCallback pointer, not a JS function.
  • Calls are synchronous on the JS thread. A slow C call blocks the event loop.
  • toBuffer(p, n, false) views and getRawPointer() dangle after free() or GC.
  • process.permission.drop('ffi') does not stop calls or getFunction() on an already-open library. Only new libraries, toFunction, and memory helpers are denied.
  • No structs by value, no calling-convention choice, fixed signatures only.

Don't

  • Don't install ffi-napi, node-ffi, ref-napi or koffi for simple calls on 26.1+.
  • Don't write a C++ addon just to call one C function.
  • Do still use Node-API/an addon when you need structs by value, threadpool work, native objects, v24 support, or a vetted safe API.

Reference

  • rules/api.md: read for type names, every DynamicLibrary method, callbacks' lifetime rules, and memory helpers.
  • rules/call-paths-safety.md: read for performance (Fast API/shared-buffer/generic paths, arg limits), permissions, and the full safety list.

perf_hooks Histogram statistics

FeatureVersionsStabilityFlag
cdf ccdf countAt percentilesAt skewness kurtosis linearBuckets logBuckets percentileCI welchTest mannWhitneyTest ksTest cohensD cliffsD ewmaStddev ewmaErrorRate burnRate recordCorrected subtractv26.8.0, v24.21.02none
ewmaMeanv26.8.0 (YAML lists no v24)2none
meanCI, importHistogramv26.9.0, v24.22.02none
export() (format v2 since v26.11.0)v26.9.02none
qrde, createSlidingWindowHistogramv26.10.0, v24.22.02none
snapshot, diff, resetCount, record(0), ELD lowest/highest/figuresv26.11.0 (not on v24)2none
ELD samplePerIterationv26.5.0, v24.19.02none
perf_hooks.eventLoopUtilization, perf_hooks.timerifyv25.2.0, v24.12.02none

Values are unitless integers: you pick the unit. monitorEventLoopDelay, timerify and recordDelta record nanoseconds; ELU is ms.

Is B significantly slower than A?

const w = a.welchTest(b);            // CI is on a.mean - b.mean
const slower = w.pValue < 0.05 && w.confidenceInterval.upper < 0;
const { pValue } = a.mannWhitneyTest(b); // skewed latency: rank test
a.cohensD(b); a.cliffsD(b); a.ksTest(b); // effect size / distance

p99 with a CI

const { value, lower, upper } = h.percentileCI(99, { confidence: 0.95 });
const m = h.meanCI();                // { mean, lower, upper }

SLO burn rate

const lat = createHistogram({ halfLife: 100, threshold: 200_000_000 }); // 200 ms in ns
lat.record(durationNs);
if (lat.burnRate(0.999) > 1) alert(); // ewmaErrorRate / (1 - 0.999)

Interval deltas and merging workers

const now = eld.snapshot();
const d = now.resetCount === prev.resetCount ? now.diff(prev) : now;
total.add(importHistogram(bytesFromWorker)); // worker sends h.export()

Pitfalls

  • record() needs integers ≥ 0 (≥ 1 before v26.11.0). performance.now() floats throw ERR_OUT_OF_RANGE.
  • Interval-mode ELD samples include resolution (min ≈ 10e6 ns at the default 10 ms). Subtract it, or use samplePerIteration: true. Don't compare the two modes.
  • Before v26.11.0, ELD lowest/highest/figures are silently ignored.
  • Sign convention: a.x(b) is "a minus b". Negative t, d or delta means a is lower.
  • With fewer than 2 samples, tests return pValue: 1 and CIs return NaN or the point value. They do not throw.
  • burnRate() without halfLife + threshold returns 0 and does not throw.
  • snapshot(), diff() and sliding-window snapshots are read-only Histograms. add() rejects them, so importHistogram(x.export()) first.
  • recordCorrected(v, i) backfills v-i, v-2i, … down to i on every call.

Don't

  • Don't hand-roll t-tests, percentile sorting or EWMA, and don't install hdr-histogram-js, simple-statistics or jstat for these.
  • On v26.11+, don't copy with createHistogram().add(total) + subtract(). Use snapshot() + diff().
  • Don't call reset() per interval when other readers share the histogram. Diff snapshots instead.

Reference

Removed APIs and changed defaults (v24 → main)

FeatureVersionsStabilityFlag
EOL removals belowv25.0.0, v26.0.0, v27.0.0-alpha.0.0.0, mainremoved—
Changed defaults belowper row——
localStorage on by defaultv25.0.01.2 RC--localstorage-file

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

v27.0.0-alpha.0.0.0 is an alpha line: no stable v27 exists yet. On v26 those rows still work but print a runtime DeprecationWarning.

Stale pattern → write instead

Each replacement already works on v24, so migrate without a version gate.

StaleWriteGone in
SlowBuffer(n)Buffer.allocUnsafeSlow(n)v25.0.0
fs.F_OK, fs.R_OK…fs.constants.F_OKv25.0.0
fs.rmdir(p, { recursive })fs.rm(p, { recursive: true, force: true })v25.0.0
assert.CallTrackermock.fn() from node:testv25.0.0
assert.fail(a, b)assert.strictEqual(a, b)v25.0.0
repl.REPLServer()new repl.REPLServer()v25.0.0
leaked FileHandleawait using fh = await open()v25.0.0 (throws)
require('node:_stream_readable')require('node:stream')v26.0.0
res.writeHeader()res.writeHead()v26.0.0
crypto.fipscrypto.getFips() / setFips()v27 alpha
zlib.Gzip()new zlib.Gzip() or zlib.createGzip()v27 alpha
createHash('shake256')createHash('shake256', { outputLength })v27 alpha
CryptoKey into node:cryptoKeyObject.from(key)v27 alpha
crypto.setEngine, clientCertEnginenone (OpenSSL providers)v27 alpha
module.register(), --loadermodule.registerHooks(): see node-modules-loadingmain
--experimental-transform-typeserasable TS only, no flag: see node-modules-loadingv26.0.0

Changed defaults

  • server.keepAliveTimeout is 65000 ms, was 5000 (v27 alpha). Set it explicitly if a proxy needs it shorter.
  • Buffer.poolSize is 65536, was 8192 (v26.3.0, v24.18.0).
  • readable.read() with no size returns one chunk (v26.0.0). Loop while ((c = r.read()) !== null).
  • localStorage without --localstorage-file is undefined plus a warning (v26.0.0, verified; the docs say it throws).
  • new DatabaseSync(path) has defensive: true by default (v25.5.0, v24.14.0).
  • fs.mkdtemp(Buffer) returns a Buffer, even with encoding: 'utf8' (v27 alpha). Pass a string prefix to get a string.

Pitfalls

  • On v26, run tests with --throw-deprecation to surface the v27/main removals.
  • http classes without new only warn (DEP0195). Add new anyway.
  • sqlite.Database (the new name for DatabaseSync) is not on v24.19. Keep using DatabaseSync while v24 is supported.

Don't

  • Don't use the util.isDate/isString/… helpers, util.log (EOL v23.0.0), crypto.createCipher (v22.0.0) or dirent.path (v24.0.0).
  • Don't load node:domain (runtime-deprecated in v27 alpha) or node:_http_*.

Reference

  • rules/removals.md: every End-of-Life since v23, with what throws and how. Read it for any API missing from the table above.
  • rules/deprecations.md: runtime and documentation-only deprecations that still work but warn.
  • rules/changed-defaults.md: every changed default with details (upgrade event, dns.reverse, REPL await, execve, largepages).

Module loading: TypeScript, require(esm), hooks, package maps

FeatureVersionsStabilityFlag
Type stripping, on by defaultStable v25.2.0, v24.12.02off: --no-strip-types
require(esm)Stable v25.4.0, v24.15.02off: --no-require-module
ERR_REQUIRE_ASYNC_MODULE .requireStackv26.5.0, v24.20.02locations: --experimental-print-required-tla
module.registerHooks()v23.5.0, v22.15.0 (RC v25.4.0, v24.13.1)1.2—
module.register(), --loaderremoved on main (DEP0205)EOL—
Package mapsv26.4.0, v24.20.01--experimental-package-map=<file>
with { type: 'text' }v26.5.0, v24.19.01.0--experimental-import-text
TS in "private": true depsv27.0.0-alpha.0.0.01--experimental-strip-private-modules
"worker" export conditionmain only (verified)1—
Wasm import sourcev24.0.0 (no flag from v24.5.0)1.2—
Compile cache portable / readOnlyv25.0.0, v24.12.0 / v26.8.02NODE_COMPILE_CACHE*
--config-filev26.12.0 (v24: --experimental-config-file)2—

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Run TypeScript directly

// node app.ts   (no flag, no tsx)
import type { User } from './types.ts';   // `type` is required; the extension too
import { load } from './load.ts';

Only erasable syntax runs. enum, runtime namespace and parameter properties throw ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX. Set tsconfig erasableSyntaxOnly.

Loader hooks (sync, in-thread, for import and require)

import { registerHooks } from 'node:module';
const hooks = registerHooks({
  resolve: (s, ctx, next) => s === 'virtual:x' ? { url: s, shortCircuit: true } : next(s, ctx),
  load: (url, ctx, next) => url === 'virtual:x'
    ? { format: 'module', source: 'export default 1', shortCircuit: true } : next(url, ctx),
});
hooks.deregister();

Preload with node --import ./hooks.mjs app.js.

require(esm)

require('./x.mjs') returns the namespace. If the graph has top-level await it throws ERR_REQUIRE_ASYNC_MODULE; use await import() instead. export { X as 'module.exports' } makes require() return X.

Pitfalls

  • When a load hook edits nextLoad() output, write { ...result, source }. The docs' { source, ...result } keeps the old source.
  • A set NODE_OPTIONS env var, even an empty one, makes --config-file ignore all of the file's nodeOptions.
  • .ts under node_modules is refused. tsconfig paths is ignored; use "imports" (#x).

Don't

  • Don't use --experimental-transform-types or mode: 'transform'. Both were removed in v26.0.0.
  • Don't use module.register() or --[experimental-]loader. They are removed on main.
  • Don't add --experimental-strip-types. Type stripping is on by default.

Reference

Node.js networking (v24+)

FeatureVersionsStabilityFlag
node:net/promises, for await (s of server)v27.0.0 (not v24/v26)1—
net.BoundSocket / { path }, isPipev26.4.0, v24.19.0 / v26.7.0, v24.20.02—
send BoundSocket via subprocess.sendv26.10.0, v24.22.02—
BlockList addCIDR[s], remove*, PRIVATE_RANGES, size, clearv26.8.0, v24.21.02—
setKeepAlive({ interval, count }), dgram bindSync/connectSyncv26.4.0, v24.19.02—
set/getTypeOfService, typeOfServicev25.6.0, v24.15.02—
TLS certificateCompressionv26.4.0, v24.19.02—
tlsSocket.socketv27.0.02—
http.isValidHeaderName/Value / websocketMask/Unmaskv26.11.0 / v26.12.02—
message.signalv26.1.0, v24.16.0 (fixed v26.7.0, v24.20.0)2—
writeInformation (http, http2)v26.2.0, v24.18.02—
httpValidation / optimizeEmptyRequestsv26.3.0, v24.19.0 / v25.1.0, v24.12.02—
setGlobalProxyFromEnv / env proxyv25.4.0, v24.14.0 / v24.5.0, v22.21.01.1--use-env-proxy
http2 http1Options, strictSingleValueFields / connectionWindowSizev25.7.0, v24.15.0 / v26.11.02—

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Reserve a port synchronously

const bound = new net.BoundSocket({ host: '127.0.0.1' }); // numeric IP, no DNS
const { port } = bound.address();       // known now, no race
net.createServer(h).listen(bound);      // adopts; or child.send('x', bound)

SSRF guard

const deny = new net.BlockList();
deny.addCIDRs(net.BlockList.PRIVATE_RANGES);
deny.check(ip, net.isIPv6(ip) ? 'ipv6' : 'ipv4');

Cancel work when the client leaves

http.createServer(async (req, res) => {
  res.writeInformation(103, { Link: '</app.css>; rel=preload' });
  const data = await fetch(upstream, { signal: req.signal });
});

Changed defaults

  • server.keepAliveTimeout is 65000 from v27 (was 5000). Set it explicitly behind a load balancer.
  • 'upgrade' with a body (v26+): the body is parsed onto req, and head/stream hold only the bytes after it. On v24 the body leaks into head.
  • dns.reverse (v27+) always sends a PTR query and ignores /etc/hosts. Use dns.lookupService(ip, port) for hosts-aware names.

Pitfalls

  • check() defaults to 'ipv4', so check('::1') is false. Pass the family.
  • optimizeEmptyRequests: no 'end' on bodyless requests (once(req, 'end') hangs); for await works.
  • req.signal on v24.16–24.19 / v26.1–26.6 also aborts after a normal response.
  • httpValidation: 'strict' rejects control chars, not non-ASCII. 'relaxed' allows control chars.
  • Certificate compression needs both peers to opt in, and TLS 1.3. v24 fetch via HTTP_PROXY uses CONNECT even for http://.

Don't

  • Don't use get-port or listen(0) races (BoundSocket), ip-range-check, bufferutil, global-agent/proxy-agent, or req.on('close') abort checks.

Reference

  • rules/net.md: net/promises, BoundSocket (IPC, workers, pipes), BlockList, keep-alive, TOS, dgram.
  • rules/tls.md: certificate compression, tlsSocket.socket.
  • rules/http.md: validators, masking, signal, 1xx, options, proxy, upgrade, keep-alive, dns.reverse.
  • rules/http2.md: http1Options, strictSingleValueFields, connectionWindowSize, writeInformation.

Node.js permission model

FeatureVersionsStabilityFlag
Permission model, fs grantsv20.0.0 (stable v23.5.0, v22.13.0)2--permission, --allow-fs-read/write
child, worker / addons / wasiv20.0.0 / v21.6.0, v20.12.0 / v22.3.0, v20.16.01.1--allow-child-process etc.
Inspector gatev25.0.0, v24.12.01.0--allow-inspector
Audit modev25.8.0, v24.20.0---permission-audit
process.permission.drop()v26.3.0, v24.20.01.1-
OpenSSL STORE gatev26.7.0, v24.21.01.1--allow-openssl-store
Network gatev25.0.0 (not v24)1.1--allow-net
FFI / VFS mount gatev26.1.0 / v26.9.0 (not v24)1.1--allow-ffi / --allow-fs-vfs
Env var filteringv27.0.0 (not v24/v26)1.1--allow-env

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

A seat belt, not a sandbox: it does not stop malicious code.

Read-only ./data plus network

node --permission --allow-fs-read=./data --allow-net untrusted.mjs

The entrypoint is implicitly readable (v24.2.0+); its imports and node_modules are not. There is no per-host network grant. --allow-net=api.example.com is accepted and grants all network. For one host, use an OS firewall, a network namespace, or a container. On v24, --permission does not gate the network at all.

Errors

// { code: 'ERR_ACCESS_DENIED', permission: 'FileSystemRead', resource: '../x' }  (path as passed)
// permission: FileSystemWrite | ChildProcess | WorkerThreads | WASI | Inspector | Net | FFI | OpenSSLStore

Net errors arrive async (connect ERR_ACCESS_DENIED, resource: ''). fetch rejects with TypeError and err.cause.code === 'ERR_ACCESS_DENIED'. Addons throw ERR_DLOPEN_DISABLED. VFS mount throws ERR_INVALID_STATE.

Drop after init (v24.20+)

const cfg = fs.readFileSync('conf/app.json');        // started with --allow-fs-read=./conf
process.permission.drop('fs.read', './conf');         // must match the grant exactly
process.permission.drop('child');                     // whole scope; irreversible

Discover needs: --permission-audit

dc.channel('node:permission-model:fs').subscribe(({ permission, resource }) => log(permission, resource));

Run with --permission-audit: nothing throws.

Pitfalls

  • has() and drop() with an unknown scope return false / do nothing, with no error. On v24, has('net') is false even though the network is open.
  • Dropping a file inside a granted directory silently does nothing.
  • new Worker(f, { execArgv: [] }) runs without the permission model.
  • --allow-child-process can escape the model; children inherit flags via NODE_OPTIONS.
  • --allow-openssl-store and --allow-ffi access is not checked against fs.read.
  • Don't pass both --permission and --permission-audit: v26.13.0 audits only.

Don't

  • --experimental-permission (bad option on v24+); vm/vm2 as a sandbox; comma-separated --allow-fs-* paths; hand-scrubbing process.env on v27+ (use --allow-env).

Reference

--process-timeout

FeatureVersionsStabilityFlag
--process-timeout=duration (exit code 124)v26.11.0 (not on v24)1.1 Active developmentitself
--report-on-process-timeoutv26.11.01.1needs --process-timeout
subprocess.timedOut, error.timedOut (exec/execFile callback)v27.0.0-alpha.0.1.0 (YAML); absent in v26.13.02none

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Make CI fail instead of hang

node --process-timeout=10m server-smoke.js     # units: ms s m h, positive integer
node --process-timeout=15m --test              # caps the whole run
node --process-timeout=5m --report-on-process-timeout --report-directory=reports app.js

When it fires, the process exits with 124 (like timeout(1), overriding process.exitCode). It prints the JS stack if the main thread was running JS, otherwise the handles keeping the loop alive:

(node:25418) Process timed out after 5s (--process-timeout). Exiting with code 124.
Main thread was not executing JavaScript.
Resources keeping the event loop alive:
    TCPServerWrap (listening on [::]:3000, fd 20)
    Timeout x2 (next due in 2931ms)

Find what keeps the process alive

Run it with a short timeout and read the resource list (TCPServerWrap, Timeout, ProcessWrap (pid N), PipeWrap…). The report's header.trigger is 'ProcessTimeout', and its libuv array lists every handle.

Child processes and node --test

  • fork() children (and any child given process.execArgv) inherit the flag and time out on their own clock, measured from their own start.
  • spawn(process.execPath, …) without execArgv does not inherit it. fork(file, { execArgv: [] }) opts a child out.
  • Children are not killed when the parent times out. They outlive it and stop only through their own timeout.
  • node --test passes the flag to each test-file process. The runner's clock starts first, so the runner usually fires first and lists the hung file only as ProcessWrap (pid N). The orphaned file process then exits on its own timeout.

Pitfalls

  • It is not allowed in NODE_OPTIONS (exit 9). Put it on the command line or in the npm script.
  • It can't be combined with --inspect*, node inspect, --run or --build-snapshot. inspector.open() throws ERR_INSPECTOR_NOT_AVAILABLE.
  • 'exit'/'beforeExit' handlers don't run. Coverage (NODE_V8_COVERAGE) and --cpu-prof output are still written.
  • A main thread blocked in native code (execSync) gets 2 s to respond, then the process exits 124 with a "did not respond" note and no stack.
  • subprocess.timedOut belongs to the timeout option of spawn/exec/execFile/fork, not to this flag. For sync APIs, check err.code === 'ETIMEDOUT'.

Don't

  • Don't wrap the command in timeout 600 node … or write setTimeout(() => process.exit(1), …).unref() watchdogs. On 26.11+ the flag gives the same exit code plus a diagnosis.
  • Don't install why-is-node-running or wtfnode just to list open handles. --process-timeout prints them.
  • Don't use --test-timeout for "the run never ends". It is per test, and tests that pass but leak a handle still hang.

Reference

  • rules/behavior.md — read for the exact output formats, error messages, exit codes, the report, and verified child-process/test-runner timing.

node:quic and node:dtls

FeatureVersionsStabilityFlag
node:quic core (connect, listen, endpoint/session/stream)v23.8.01.0--experimental-quic (flag added v25.0.0, v24.16.0)
QUIC alpn/sni optionsv26.1.0, v24.16.01.0same
session.opened, stream.writer/setBody/async iteration, HTTP/3v26.2.0, v24.20.01.0same
node:dtls listen/connect, PSK, SNIv26.9.01.1--experimental-dtls
dtls.createSecureContext, session.session/reused/authorizedv26.10.01.1same

Both are compile-time options too. The official v24.19.0 and v26.13.0 binaries and a default main build don't include them. require then throws ERR_UNKNOWN_BUILTIN_MODULE even with the flag. You need a build made with ./configure --experimental-quic --experimental-dtls and the runtime flag. Check with node -p process.config.variables.node_use_quic (node_use_dtls). DTLS is not on v24.

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Model

  • QUIC: a QuicEndpoint (UDP socket) carries QuicSessions (TLS 1.3), which carry QuicStreams. Events are callback properties (onstream, onerror). opened and closed are promises.
  • DTLS: a DTLSEndpoint carries DTLSSessions that exchange datagrams (send, onmessage).

QUIC echo (verified on a QUIC build of main)

const pem = new TextEncoder().encode(certPem);          // PEM *bytes*; keys = KeyObject
const ep = await quic.listen((s) => { s.onstream = async (st) => {
  st.setBody('echo:' + await text(st)); }; },            // for await (const chunks of st)
  { alpn: ['demo'], sni: { '*': { keys: [key], certs: [pem] } },
    endpoint: { address: '127.0.0.1:0' } });
const c = await quic.connect(ep.address, { alpn: 'demo', servername: 'localhost', ca: [pem] });
await c.opened;
const st = await c.createBidirectionalStream({ body: 'hello' });

DTLS echo

const srv = dtls.listen((s) => { s.onmessage = (d) => s.send(d); },
  { cert, key, host: '127.0.0.1', port: 0 });            // sync; port required
const c = dtls.connect('127.0.0.1', srv.address.port, { ca: cert, servername: 'localhost' });
await c.opened; c.send('ping');                          // send only after opened

Pitfalls

  • QUIC defaults to ALPN 'h3'. Set alpn on both sides for a raw protocol. The server needs sni (use '*' as the fallback).
  • QUIC verifyPeer: 'auto' rejects self-signed certs without ca. 'manual' exposes validationErrorCode (a string).
  • Read every QUIC stream to the end, or Stream.dump() it. A stream takes a body or the writer, not both.
  • dtls.connect takes an IP literal (no DNS). send is at most 16384 B and throws before opened.
  • A wrong DTLS PSK or no common cipher makes the handshake go silent. Set handshakeTimeout (default 60 s).
  • Both need --allow-net under --permission.

Don't

  • Don't assume node:quic/node:dtls exist because the version is new enough. Check process.config and tell the user if a custom build is needed.
  • Don't promise HTTP/3 fetch(). node:quic is low-level framing only.

Reference

  • rules/quic-api.md: read for the QUIC endpoint/session/stream API, all options, stats, HTTP/3, datagrams, 0-RTT.
  • rules/dtls-api.md: read for DTLS options, PSK, SNI, resumption, ticket keys, DoS limits, SRTP, stats.

node:sqlite (current API)

FeatureVersionsStabilityFlag
module, DatabaseSync/StatementSyncv22.5.0; unflagged v23.4.0, v22.13.01.2 RC (v25.7.0, v24.15.0)none
createTagStore, SQLTagStorev24.9.01.2none
setAuthorizerv24.10.01.2none
defensive, enableDefensivev25.1.0, v24.12.0; on by default v25.5.0, v24.14.01.2none
database.limitsv25.8.0, v24.15.01.2none
serialize, deserializev26.1.0, v24.16.01.2none
bind boolean, ArrayBufferv26.8.0, v24.21.01.2none
statement.close, statement[Symbol.dispose]v26.8.0, v24.22.01.2none
'sqlite.db.query' channelv26.8.0, v24.22.01none
stat, resetStats, prepare({ persistent })v26.8.0 (not v24)1.2none
bind undefined as NULLv26.10.0 (not v24)1.2none
Database/Statement names, createModulev26.11.0 (not v24)1.2none

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Portable import

import * as sqlite from 'node:sqlite';
const Database = sqlite.Database ?? sqlite.DatabaseSync; // v24 has only DatabaseSync

On v24, import { Database } is a link-time SyntaxError.

Tagged-template queries

const db = new Database('app.db');
const sql = db.createTagStore(); // LRU cache of prepared statements (default 1000)
sql.run`INSERT INTO users(name) VALUES (${name})`; // ${} binds; it never interpolates
const user = sql.get`SELECT * FROM users WHERE id = ${id}`;

Statements and disposal

using db = new Database(':memory:');
{
  using stmt = db.prepare('INSERT INTO t VALUES (?, ?)'); // v24.22+/v26.8+
  stmt.run(1n, 'a');
} // finalized here

Untrusted SQL

const { constants: c } = sqlite;
const ok = new Set([c.SQLITE_SELECT, c.SQLITE_READ, c.SQLITE_FUNCTION]);
db.setAuthorizer((action) => (ok.has(action) ? c.SQLITE_OK : c.SQLITE_DENY));
db.limits.sqlLength = 10_000; // or new Database(p, { limits: { ... } })

Pitfalls

  • A JS number always binds as REAL. Use a bigint where INTEGER matters (TEXT or untyped columns, expressions, virtual tables).
  • Before v24.21, a boolean throws and an ArrayBuffer silently binds NULL. Pass BigInt(flag) and new Uint8Array(ab) instead.
  • Before v26.10, an anonymous undefined parameter throws. Use null.
  • Never put ? in tag-store SQL. v24.22+ and v26 throw ERR_INVALID_ARG_VALUE, while v24.19 silently binds NULL.
  • Defensive mode blocks writable_schema edits. Use { defensive: false } only for legacy tooling.
  • The authorizer must not use its own connection. Since v24.22 that throws ERR_INVALID_STATE; older versions recurse.
  • On v24, prepare({ persistent }) is silently ignored. All calls are synchronous.

Don't

  • Don't add better-sqlite3/sqlite3 when node:sqlite covers the need, and don't pass --experimental-sqlite.
  • Don't build SQL with string concatenation or with an untagged template passed to exec(). Use the tag store or ? parameters.
  • Don't write DatabaseSync in code that only targets v26.11+.

Reference

  • rules/api.md: constructor options, every Database/Statement/SQLTagStore method, binding rules
  • rules/security.md: authorizer action codes, defensive mode, limits, untrusted database files
  • rules/advanced.md: createModule, serialize, stat counters, diagnostics channel, sessions, backup

node:stream/iter (iterable streams)

FeatureVersionsStabilityFlag
node:stream/iterv25.9.0, v24.20.01--experimental-stream-iter
filehandle.pull, pullSync, writerv25.9.0, v24.20.01same
node:zlib/iter (compress*/decompress*, *Sync)v25.9.0, v24.20.0 (the docs list only v25.9.0)1same
from/toReadable, from/toWritable, Readable[Symbol.for('Stream.toAsyncStreamable')]v26.1.0, v24.20.01same
dump, dumpSyncv26.12.0 (not v24)1same

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Mental model

  • A stream is any AsyncIterable or Iterable of batches (Uint8Array[]). Strings become UTF-8 bytes.
  • A transform is (chunks | null) => chunks (null means flush) or { transform: async function* (source) {} }.
  • pull() is lazy, so the consumer sets the pace. push() returns { writer, readable } with a byte budget.
  • A writer is any object with write(). Its other methods are optional.
  • Without the flag the import throws, and v24.19 and older reject the flag itself.

File → transform → file

import { open } from 'node:fs/promises';
import { pipeTo } from 'node:stream/iter';
import { compressGzip } from 'node:zlib/iter';
const src = await open('in.txt'), dst = await open('in.txt.gz', 'w');
await pipeTo(src.pull({ autoClose: true }), compressGzip(), dst.writer({ autoClose: true }));

Consume to text or bytes

const s = await text(pull(from(gzBytes), decompressGzip()), { limit: 1 << 20 });
const b = await bytes(fh.pull({ start: 100, limit: 1024, autoClose: true }));

Interop

await text(from(classicReadable)); // or a web ReadableStream
await pipeline(toReadable(pull(src, compressGzip())), res);
await pipeTo(src, fromWritable(writable, { backpressure: 'unbounded' }));

Push with backpressure

const { writer, readable } = push(); // 16384-byte budget, 'strict' policy
const done = text(readable);                          // run the consumer concurrently
for (const item of items) await writer.write(item);   // must await
await writer.end();

Pitfalls

  • v24.x, and v26 before 26.12: a budget below 16384 throws, and pull() with a pre-aborted signal throws synchronously (rules/versions.md).
  • Under 'strict', an unawaited write() rejects with ERR_INVALID_STATE. Without a consumer, writes wait forever.
  • Compression transforms keep state, so make one per pipeline. The defaults are gzip level 4 and brotli quality 6.
  • Without autoClose, close the FileHandle yourself.

Don't

  • Don't subclass Transform here. Write a function or generator transform.
  • Don't use zlib.createGzip() in a pipeline. Use compressGzip() from node:zlib/iter.

Reference

node:test: what is new since v24

FeatureVersionsStabilityFlag
tags, context.tags, run({ testTagFilters })v26.2.0, v24.19.0 ¹1.0--experimental-test-tag-filter=<expr>
Random order, run({ randomSeed })v26.1.0, v24.16.01.0--test-randomize, --test-random-seed=<n>
Rerun failed onlyv24.7.02--test-rerun-failures=<file>
Global setup/teardownv24.0.01.0--test-global-setup=<module>
expectFailurev25.5.0, v24.14.02
t.workerIdv25.8.0, v24.15.02
t.attemptv25.0.0 ²2
node.test tracing channelv26.1.0, v24.16.02
getTestContext()v26.1.0, v24.19.02
t.log(), 'test:log'v26.6.0, v24.20.02
run({ env })v25.6.0, v24.14.02
Include never-loaded filesv26.7.01--test-coverage-include-all
t.assert.called, callCount, nthCalledWith, lastCalledWithv26.12.02
mock.mockReturnValue & co.v27.0.02
Forbid .onlyv27.0.02--test-forbid-only
Watch mode Stablev27.0.02--test --watch

¹ v24.19.0 matches plain tag names only (repeat the flag to AND); &&, !, not, * select nothing. ² Docs say v25.0.0; also works on v24.19.0.

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Mocks

const send = t.mock.fn();
send.mock.mockReturnValue(true);            // 27+, returns undefined (not chainable)
notify(send);
t.assert.callCount(send, 2);                // 26.12+
t.assert.nthCalledWith(send, 1, 'a@x.dev'); // 1-based, deepStrictEqual on args
t.assert.lastCalledWith(send, 'b@x.dev');

Tags, expected failures, CI flags

describe('db', { tags: ['db'] }, () => {    // children inherit tags by union
  it('reconnects', { tags: ['flaky'] }, () => {});
  it('parses', { expectFailure: /unsupported/ }, () => parse('x')); // passes only if it throws a match
});
node --test --experimental-test-tag-filter='db && !flaky'  # grammar: 26.2+
node --test --test-forbid-only --test-rerun-failures=.test-state.json
node --test --test-random-seed=1234        # replay a printed seed

Pitfalls

  • Random order cannot be combined with --test-rerun-failures or --watch. Awaiting subtests one at a time keeps declaration order.
  • run({ env }) replaces process.env for children (even PATH) and throws with isolation: 'none'.
  • Rerun state is keyed by file:line:column: moving a test resets it.
  • Unknown flags fail with bad option; unknown run() options (forbidOnly on v24) are silently ignored.

Don't

  • toHaveBeenCalledWith → t.assert.nthCalledWith/lastCalledWith (before 26.12: fn.mock.calls[i].arguments).
  • jest.fn().mockReturnValue(x) before 27 → t.mock.fn(() => x).
  • test.failing → expectFailure; --forbid-only → --test-forbid-only; --shuffle/seed → --test-random-seed.
  • JEST_WORKER_ID → t.workerId / NODE_TEST_WORKER_ID. Tags in test names + --test-name-pattern → tags.

Reference

Utilities since v24

FeatureVersionsStabilityFlag
util.debounce, throttle, markPromiseAsHandledv26.10.0, v24.22.02
util.isPartialDeepStrictEqual, Buffer.stringLength, isLatin1v26.11.02
util.convertProcessSignalToExitCode; streamConsumers.bytesv25.4.0; v25.6.0; both v24.14.02
styleText('#rrggbb'), glob({ followSymlinks })v26.1.0, v24.16.02
fs.mkdtempDisposable[Sync]v24.4.02
fs.mkstemp[Sync]v27.0.01
fs.Utf8Streamv24.6.01
glob({ maxDepth }); fs.openAsBlobSyncv26.9.0; v26.10.02
async stat({ throwIfNoEntry })v25.7.0 (also v24.19.0)2
stat/lstat signal; allocUnsafe(n, alignment)v26.8.02
Stats *Instant (Temporal)v26.2.02
blob.textStream(), ReadableStreamTeev26.5.0, v24.19.02, 1
URLPattern globalv24.0.01
navigator.locks, worker_threads.locksv24.5.01
ErrorEvent; QuotaExceededErrorv25.0.0; v26.0.02
Global Web Workerv26.9.0, default-on in main1--experimental-web-worker
process.addUncaughtExceptionCaptureCallbackv25.9.01
process.ref/unref Stablev26.11.0 (added v23.6.0, v22.14.0)2
tty setRawMode('raw'|'io'), rawModev26.8.0, v24.21.02
stream.compose Stablev26.2.0, v24.19.02
assert.Assert; skipPrototypev24.6.0, v22.19.0; v24.9.02

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Patterns

import { debounce, throttle } from 'node:util';
const save = debounce(async (doc) => write(doc), 300); // all callers get the last result
save.cancel(); // pending reject with AbortError
const get = throttle((id) => load(id), 2, 1000); // 2 starts/s; extras queue

await using dir = await fsp.mkdtempDisposable(join(tmpdir(), 'job-')); // rm -r at scope exit
const { path, handle } = await fsp.mkstemp(join(dir.path, 'f-')); // 27+, mode 0600
await using h = handle; // the result is not disposable

new URLPattern({ pathname: '/users/:id(\\d+)' }).exec(url)?.pathname.groups.id;
await navigator.locks.request('cache', () => refresh()); // resolves with refresh()'s value

Pitfalls

  • Older versions ignore new args silently: allocUnsafe(n, 3), glob({ maxDepth }); setRawMode('io') acts as raw.
  • mkdtempDisposable(Buffer) throws on main after creating the directory.
  • using on fs.Utf8Stream calls destroy() and drops buffered data. Call end().
  • Locks are per process. A queued request does not keep a worker alive.
  • new Worker('./w.js') resolves against cwd; pass a URL.

Don't

  • lodash.debounce/throttle, p-throttle → util.debounce/throttle.
  • tmp/tmp-promise → mkdtempDisposable/mkstemp; sonic-boom → Utf8Stream.
  • urlpattern-polyfill → URLPattern; in-process async-mutex → navigator.locks (not proper-lockfile: cross-process).
  • chalk.hex() → styleText('#hex'); 128 + signals[s] → convertProcessSignalToExitCode.

Reference

node:vfs and VFS-backed single executables

FeatureVersionsStabilityFlag
node:vfs: create, MemoryProvider, RealFSProviderv26.4.0126.x: --experimental-vfs; v27+: none (--no-experimental-vfs disables)
mount/unmount/mountPointURL, ZipProvider, --allow-fs-vfsv26.9.01 / 1.1as above
registerProvider, --vfs-loadv26.10.01as above
vfsBase() · ComposableProviderv26.11.0 · v26.12.01as above
--build-seav25.5.01.1none
SEA "useVfs", "vfsArchive"v26.9.01.0none

None of this exists on v24. Feature-detect with node -e "require('node:vfs').create().mount" (plus --experimental-vfs on 26.x).

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

Mount, then use ordinary fs/require/import

import vfs from 'node:vfs';
using v = vfs.create();                    // MemoryProvider; unmounts at scope end
v.writeFileSync('/mod.mjs', 'export default 42');   // seed BEFORE mount
const root = v.mount();                    // e.g. /dev/null/vfs/1 — never hard-code
fs.readFileSync(`${root}/mod.mjs`, 'utf8');
await import(`${v.mountPointURL}/mod.mjs`); // use the file: URL for import()

Code under test should take root as a parameter; VFS cannot fake fixed real paths. Load from a zip: vfs.create(new vfs.ZipProvider(new zlib.ZipBuffer(bytes))), or run a whole app: node --vfs-load=app.zip (runs its package.json "main").

Single executable with assets

sea-config.json: {"main":"main.js","output":"app","useVfs":true,"assets":{"config.json":"src/config.json"}}, then node --build-sea sea-config.json. Inside, __dirname is the read-only mount root: fs.readFileSync(path.join(__dirname, 'config.json')), require('./lib/x.js'). Or set "vfsArchive": "assets.zip" instead of assets.

Pitfalls

  • While mounted, the instance's own methods need mount-prefixed paths too; v.readFileSync('/a') throws ENOENT until unmount().
  • The mount is in-process: child processes, fs.glob, and fs.cp don't see it. Copying to the real fs fails with EXDEV.
  • --permission makes mount() throw ERR_INVALID_STATE without --allow-fs-vfs.
  • Not a sandbox: RealFSProvider reads follow symlinks outside its root.
  • --vfs-load is rejected in NODE_OPTIONS. SEA: useVfs excludes useSnapshot; useCodeCache+useVfs needs v27+; vfsArchive needs useVfs and excludes assets.
  • With vfsArchive, sea.getAsset() can't read the files. Use fs.

Don't

  • Don't add memfs/mock-fs/unionfs where VFS fits (26.4+). Keep them for v24 and for faking fixed absolute paths.
  • Don't use postject or --experimental-sea-config on 25.5+; use --build-sea.
  • Don't write SEA assets to a temp dir to require them; use useVfs.

Reference

  • rules/api.md: read for the full VirtualFileSystem method list, providers, custom providers, registerProvider, the reserved root, and module-loader rules.
  • rules/sea.md: read when writing a --build-sea config: every field, useVfs/vfsArchive/code cache, workers, and validation errors.
  • rules/flags-security.md: read for flags per version, --vfs-load details, the permission model, and security limits.

ZIP archives in node:zlib

FeatureVersionsStabilityFlag
ZipFile, ZipBuffer, ZipEntry, zipFiles, createZipArchive[Sync], get/setMaxZipContentSizev26.8.0 (not v24, not v25)1.0 Early developmentnone
zipEntry.rawContent() method, rawContentSync, rawContentIteratorv27.0.0-alpha.0.0.0 (on v26.x rawContent is a getter)1.0none
zlib.crc32cv27.0.0-alpha.0.0.02 (zlib)none

Experimental API. Before relying on these details, run the node-experimental-check skill's probe (or node --version plus a feature-detect one-liner) and check the docs for the installed version: https://nodejs.org/docs/<version>/api/<module>.html. If the installed version disagrees with this skill, the installed version wins.

First use prints an ExperimentalWarning. Feature-detect with typeof zlib.ZipFile === 'function'.

Create a zip of files

import { zipFiles, ZipEntry, createZipArchive } from 'node:zlib';
await pipeline(zipFiles([['/src/a.pdf', 'a.pdf'], ['/src/docs', 'docs/']]), createWriteStream('out.zip'));
// In memory: build entries, then serialize them to a Readable
const entries = [await ZipEntry.create('hi.txt', Buffer.from('hi')), ZipEntry.createStream('big.bin', createReadStream(p))];
await pipeline(createZipArchive(entries, 'comment'), createWriteStream('out.zip'));

zipFiles does not walk directories, so list every path.

Read / extract

await using zip = await ZipFile.open('in.zip');        // reads only the central directory
for (const [name, pending] of zip.entries()) {          // values are Promise<ZipEntry>
  const e = await pending;
  const dest = path.resolve(root, name);
  if (!dest.startsWith(root + path.sep) || e.isSymlink) continue; // Zip Slip: names are verbatim
  if (e.isDirectory) await mkdir(dest, { recursive: true });
  else await writeFile(dest, await e.content());       // verifies CRC, capped at 256 MiB
}

Stream a large entry

await pipeline(await zip.stream('huge.bin'), createWriteStream('huge.bin'));

Append to an existing zip

await using zip = await ZipFile.open('a.zip', { writable: true }); // the file must exist
await zip.add('new.txt', data);   // replaces same-name entries; written on resolve
await zip.delete('old.txt');      // rewrites the central directory only
await pipeline(zip.compact(), createWriteStream('a.compact.zip')); // drop dead space

Pitfalls

  • Names are never normalized. You must guard .., absolute paths, drive letters, and symlink targets.
  • content() uses getMaxZipContentSize() (256 MiB) as its cap. contentIterator()/stream() have no cap unless you pass maxSize.
  • Iterator chunks are unverified until the CRC check at the end.
  • In-place edits are not crash-atomic. Write to a copy, or compact() into a new file.
  • ZipBuffer is a zero-copy view, so don't mutate its source. createZipArchive keeps duplicate names.
  • After close(), entry reads throw ERR_INVALID_STATE.

Don't

  • Don't add adm-zip, jszip, archiver, yauzl, or unzipper on 26.8+. On v24, a package is still needed.
  • Don't use zlib.gzip to make a ".zip". Gzip is not the ZIP format.
  • For gzip/zstd/brotli transforms in iterable pipelines, see the node-stream-iter skill.

Reference

  • rules/api.md: every ZipFile/ZipBuffer/ZipEntry member, options, and error codes
  • rules/security.md: untrusted archives, zip bombs, Zip Slip, CRC, durability
  • rules/versions.md: the v26 vs v27 differences (rawContent, crc32c) and portable detection

Sponsors

Details

Marketplace
jasnell/node-skills
Category
Community