
node-skills
Skills covering Node.js features added since v24, plus removals and changed defaults.
- GitHub stars
- 6
Install
/plugin install node-skills@node-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add jasnell/node-skills.
Contents
Discovered from sourceSkills 18
node:bench
| Feature | Versions | Stability | Flag |
|---|---|---|---|
node:bench (bench, suite, describe, hooks, createRunner, run, runFile), node:bench/reporters | v26.9.0 (not on v24) | 1.0 Early development | --experimental-bench |
--bench and --bench-* flags (except --bench-gc) | v26.9.0 | 1 Experimental | --experimental-bench |
doNotOptimize, --bench-gc, the gc option, end() defaulting to 1 op, the bench:environment record | added: REPLACEME (main only; absent in v26.13.0) | 1.0 | --experimental-bench |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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
fnonce with a new context, andfnmust callstart()+end()orrecord()exactly once.beforeEachruns once per benchmark, not per sample. - A loop whose result is unused can be eliminated. The
specreporter flags ≥ 1 op/ns asimplausible. Validate an aggregate, or usedoNotOptimize(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-gcadds it to children automatically, except with--bench-isolation=none. On v26.13gcis silently ignored.--benchcan't be combined with--test,--watch,--evalor--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,mitataorcronometrowhen Node ≥ 26.9 is available. Usenode: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 → feature | Versions | Stability | Flag |
|---|---|---|---|
Hash a password → argon2/argon2Sync | v24.7.0 | 2 | |
Post-quantum key exchange → 'ml-kem-768' + encapsulate | v24.7.0 | 2 | |
PQ signatures → 'ml-dsa-65'; 'slh-dsa-*' | v24.6.0; v24.8.0 | 2 | |
WebCrypto ML-KEM/ML-DSA/Argon2/KMAC/SHA3/cSHAKE/OCB/ChaCha20, getPublicKey, supports | v24.7.0, v24.8.0 | 1.1 | |
WebCrypto hybrid KEM MLKEM768-X25519 | v26.10.0, v24.22.0 | 1.1 | |
| WebCrypto TurboSHAKE, KT128 | v25.9.0, v24.18.0 | 1.1 | |
createMac/getMacs | v26.9.0, v24.22.0 | 1.2 | |
| AES-SIV, AES-GCM-SIV | v26.8.0, v24.22.0 | 2 | |
Time-ordered ids → randomUUIDv7() | v26.1.0, v24.16.0 | 2 | |
.p12 → parsePKCS12 | v26.10.0, v24.22.0 | 2 | |
Self-signed cert for tests → generateX509CertificateSync, new x509.* getters | v27.0.0 (not v24/v26) | 1.2 | |
'raw-public'/'raw-private'/'raw-seed' formats | v24.15.0 | 2 | |
createPrivateKey(new URL(…)) (OpenSSL STORE) | v26.7.0, v24.21.0 | 1.1 | --allow-openssl-store |
crypto.fips.indicator channel | v26.9.0, v24.22.0 | 1 | --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-checkskill's probe (ornode --versionplus 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')isfalse(noiv).- v27+ rejects
CryptoKeyinnode:crypto: useKeyObject.from()(extractable keys only). - Short GCM tags need
authTagLengthon the decipher (v26+).setEngineis 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
- rules/post-quantum.md — PQ key types, sizes, hybrid KEM
- rules/passwords.md — Argon2 params, verify, WebCrypto
- rules/hashing-and-mac.md — SHA-3, XOFs, KMAC,
createMac - rules/ciphers.md — OCB, SIV, GCM-SIV, tag rules
- rules/certificates.md — X.509 options, getters, PKCS#12
- rules/keys-store-fips.md — raw keys, STORE, FIPS
- rules/webcrypto.md —
supports(), matrix,raw-secret - rules/removals.md — deprecations and fixes
Node.js diagnostics (v24+)
| Feature | Versions | Stability | Flag |
|---|---|---|---|
TracingChannel | v19.9.0, v18.19.0 (Stable in v26.8.0) | 2 | — |
boundedChannel, channel.withStoreScope | v26.1.0 (not v24) | 1 | — |
als.withScope / RunScope | v25.9.0, v24.20.0 | 1 | — |
AsyncLocalStorage({ defaultValue, name }) | v24.0.0 | 2 | — |
v8.startCpuProfile (sync) | v25.0.0, v24.12.0 | — | — |
v8.startHeapProfile (sync) | v26.1.0 (not v24) | 1 | — |
v8.setHeapProfileNearHeapLimit | v26.9.0 (not v24) | 1 | — |
worker.startCpuProfile / .startHeapProfile | v24.8.0 / v24.9.0, v22.20.0 | 2 | — |
node inspect --probe | v26.1.0, v24.16.0; JSON v2 + --max-hit v26.4.0, v24.19.0; --cond v26.6.0, v24.20.0 | 1 | — |
inspector DOMStorage.* | v25.5.0, v24.16.0 | 1.1 | --experimental-storage-inspection |
| Built-in channels | see rules/diagnostics-channel.md | 1 | — |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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
usingscope opened in anasyncfunction before the firstawaitleaks into the caller; useals.run(). boundedChannel.run()sets neitherctx.resultnorctx.error. A bound store makeshasSubscriberstrue.tracePromise(v26+) returns thenables as-is, non-thenables with a warning; v24 wraps both in a Promise.defaultValueapplies only when no store was entered;run(undefined)/exit()giveundefined.- One heap profile at a time.
setHeapProfileNearHeapLimitneeds an activestartHeapProfile(). - Before v24.20,
--condis rejected with a misleading "Use --" usage error. v8.queryObjectsis documented Stable but still warnsExperimentalWarning.
Don't
- Don't monkey-patch modules or use
async_hooks.createHookfor tracing: use channels +bindStore. - Don't use
enterWith()for block scope (withScope()) orconsole.logedits to inspect values (--probe).
Reference
- rules/diagnostics-channel.md: bounded channels, scopes, tracePromise history, built-in channel names.
- rules/async-context.md:
withScope/RunScope, constructor options. - rules/profiling.md: handle options, output formats, near-heap-limit, workers,
queryObjects. - rules/probe-mode.md:
--probesyntax, JSON v2 schema, terminal events, exit codes. - rules/inspector.md: Network/DOMStorage CDP events and flags.
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)
- Find the runtime that will run the code. Run
node --version, but also check.nvmrc,package.jsonengines,volta, the DockerfileFROM node:<tag>, and the CInode-version. The shell'snodemay not be the one that matters. - Probe the exact items you will use. Run the bundled script with the
target binary:
The probe passesnode 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--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"andnode --help | grep -- --flag. - Read the docs for that version, not
latest:https://nodejs.org/docs/<version>/api/<module>.html. For a pre-release build, readdoc/api/<module>.mdin its checkout. Check the YAMLadded:/changes:history and the Stability line of each API you use. - Prefer behavior over docs. For anything subtle (defaults, units, error codes), run a 5-line script instead of trusting prose.
- Gate or fall back. If the code must run on several versions, use
feature detection (
typeof x === 'function', atry { await import() }block), not a version-string compare. State the minimum version inenginesor in a comment. - 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
| Feature | Versions | Stability | Flag |
|---|---|---|---|
node:ffi (dlopen, DynamicLibrary, memory helpers) | v26.1.0 | 1 | none; --no-experimental-ffi disables |
--allow-ffi (permission model) | v26.1.0 | 1.1 | with --permission |
getCurrentEventLoop() | v26.6.0 | 1 | none |
dlopen of a path inside a mounted node:vfs | v26.10.0 | 1 | none |
library.toFunction() | main only (no YAML; absent in v26.13.0) | 1 | none |
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-checkskill's probe (ornode --versionplus 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)andbooltruethrowERR_INVALID_ARG_VALUE. Pass0/1forbool. - A
'string'return is a bigint pointer. Decode it withffi.toString(). - Wrong signatures are not detected. Declaring
boolfor a Cinttruncates 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 aregisterCallbackpointer, not a JS function. - Calls are synchronous on the JS thread. A slow C call blocks the event loop.
toBuffer(p, n, false)views andgetRawPointer()dangle afterfree()or GC.process.permission.drop('ffi')does not stop calls orgetFunction()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-napiorkoffifor 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
| Feature | Versions | Stability | Flag |
|---|---|---|---|
cdf ccdf countAt percentilesAt skewness kurtosis linearBuckets logBuckets percentileCI welchTest mannWhitneyTest ksTest cohensD cliffsD ewmaStddev ewmaErrorRate burnRate recordCorrected subtract | v26.8.0, v24.21.0 | 2 | none |
ewmaMean | v26.8.0 (YAML lists no v24) | 2 | none |
meanCI, importHistogram | v26.9.0, v24.22.0 | 2 | none |
export() (format v2 since v26.11.0) | v26.9.0 | 2 | none |
qrde, createSlidingWindowHistogram | v26.10.0, v24.22.0 | 2 | none |
snapshot, diff, resetCount, record(0), ELD lowest/highest/figures | v26.11.0 (not on v24) | 2 | none |
ELD samplePerIteration | v26.5.0, v24.19.0 | 2 | none |
perf_hooks.eventLoopUtilization, perf_hooks.timerify | v25.2.0, v24.12.0 | 2 | none |
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 throwERR_OUT_OF_RANGE.- Interval-mode ELD samples include
resolution(min ≈ 10e6 ns at the default 10 ms). Subtract it, or usesamplePerIteration: true. Don't compare the two modes. - Before v26.11.0, ELD
lowest/highest/figuresare 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: 1and CIs returnNaNor the point value. They do not throw. burnRate()withouthalfLife+thresholdreturns0and does not throw.snapshot(),diff()and sliding-window snapshots are read-onlyHistograms.add()rejects them, soimportHistogram(x.export())first.recordCorrected(v, i)backfillsv-i, v-2i, …down toion every call.
Don't
- Don't hand-roll t-tests, percentile sorting or EWMA, and don't install
hdr-histogram-js,simple-statisticsorjstatfor these. - On v26.11+, don't copy with
createHistogram().add(total)+subtract(). Usesnapshot()+diff(). - Don't call
reset()per interval when other readers share the histogram. Diff snapshots instead.
Reference
- rules/inference.md — read for exact test return shapes, choosing a test, and edge cases.
- rules/distribution.md — read for cdf, buckets (key semantics), and qrde options.
- rules/online-slo.md — read for EWMA, burnRate, recordCorrected, and sliding-window options.
- rules/lifecycle.md — read for snapshot/diff errors, export format, workers, and bigint getters.
- rules/event-loop.md — read for monitorEventLoopDelay options, units, ELU, and timerify.
Removed APIs and changed defaults (v24 → main)
| Feature | Versions | Stability | Flag |
|---|---|---|---|
| EOL removals below | v25.0.0, v26.0.0, v27.0.0-alpha.0.0.0, main | removed | — |
| Changed defaults below | per row | — | — |
localStorage on by default | v25.0.0 | 1.2 RC | --localstorage-file |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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.
| Stale | Write | Gone in |
|---|---|---|
SlowBuffer(n) | Buffer.allocUnsafeSlow(n) | v25.0.0 |
fs.F_OK, fs.R_OK… | fs.constants.F_OK | v25.0.0 |
fs.rmdir(p, { recursive }) | fs.rm(p, { recursive: true, force: true }) | v25.0.0 |
assert.CallTracker | mock.fn() from node:test | v25.0.0 |
assert.fail(a, b) | assert.strictEqual(a, b) | v25.0.0 |
repl.REPLServer() | new repl.REPLServer() | v25.0.0 |
leaked FileHandle | await 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.fips | crypto.getFips() / setFips() | v27 alpha |
zlib.Gzip() | new zlib.Gzip() or zlib.createGzip() | v27 alpha |
createHash('shake256') | createHash('shake256', { outputLength }) | v27 alpha |
CryptoKey into node:crypto | KeyObject.from(key) | v27 alpha |
crypto.setEngine, clientCertEngine | none (OpenSSL providers) | v27 alpha |
module.register(), --loader | module.registerHooks(): see node-modules-loading | main |
--experimental-transform-types | erasable TS only, no flag: see node-modules-loading | v26.0.0 |
Changed defaults
server.keepAliveTimeoutis 65000 ms, was 5000 (v27 alpha). Set it explicitly if a proxy needs it shorter.Buffer.poolSizeis 65536, was 8192 (v26.3.0, v24.18.0).readable.read()with no size returns one chunk (v26.0.0). Loopwhile ((c = r.read()) !== null).localStoragewithout--localstorage-fileisundefinedplus a warning (v26.0.0, verified; the docs say it throws).new DatabaseSync(path)hasdefensive: trueby default (v25.5.0, v24.14.0).fs.mkdtemp(Buffer)returns a Buffer, even withencoding: 'utf8'(v27 alpha). Pass a string prefix to get a string.
Pitfalls
- On v26, run tests with
--throw-deprecationto surface the v27/main removals. httpclasses withoutnewonly warn (DEP0195). Addnewanyway.sqlite.Database(the new name forDatabaseSync) is not on v24.19. Keep usingDatabaseSyncwhile v24 is supported.
Don't
- Don't use the
util.isDate/isString/… helpers,util.log(EOL v23.0.0),crypto.createCipher(v22.0.0) ordirent.path(v24.0.0). - Don't load
node:domain(runtime-deprecated in v27 alpha) ornode:_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
| Feature | Versions | Stability | Flag |
|---|---|---|---|
| Type stripping, on by default | Stable v25.2.0, v24.12.0 | 2 | off: --no-strip-types |
require(esm) | Stable v25.4.0, v24.15.0 | 2 | off: --no-require-module |
ERR_REQUIRE_ASYNC_MODULE .requireStack | v26.5.0, v24.20.0 | 2 | locations: --experimental-print-required-tla |
module.registerHooks() | v23.5.0, v22.15.0 (RC v25.4.0, v24.13.1) | 1.2 | — |
module.register(), --loader | removed on main (DEP0205) | EOL | — |
| Package maps | v26.4.0, v24.20.0 | 1 | --experimental-package-map=<file> |
with { type: 'text' } | v26.5.0, v24.19.0 | 1.0 | --experimental-import-text |
TS in "private": true deps | v27.0.0-alpha.0.0.0 | 1 | --experimental-strip-private-modules |
"worker" export condition | main only (verified) | 1 | — |
Wasm import source | v24.0.0 (no flag from v24.5.0) | 1.2 | — |
Compile cache portable / readOnly | v25.0.0, v24.12.0 / v26.8.0 | 2 | NODE_COMPILE_CACHE* |
--config-file | v26.12.0 (v24: --experimental-config-file) | 2 | — |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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
loadhook editsnextLoad()output, write{ ...result, source }. The docs'{ source, ...result }keeps the old source. - A set
NODE_OPTIONSenv var, even an empty one, makes--config-fileignore all of the file'snodeOptions. .tsundernode_modulesis refused. tsconfigpathsis ignored; use"imports"(#x).
Don't
- Don't use
--experimental-transform-typesormode: '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
- rules/typescript.md: stripping rules, flags per version,
stripTypeScriptTypes, private packages. - rules/require-esm.md: require(esm) rules,
__esModule, error properties. - rules/hooks.md: the
registerHookscontract, formats, migrating fromregister(). - rules/package-maps.md: map format, resolution and errors.
- rules/more-loading.md: text and Wasm imports, the
"worker"condition,import.meta.main(v24.2.0), compile cache,--config-file.
Node.js networking (v24+)
| Feature | Versions | Stability | Flag |
|---|---|---|---|
node:net/promises, for await (s of server) | v27.0.0 (not v24/v26) | 1 | — |
net.BoundSocket / { path }, isPipe | v26.4.0, v24.19.0 / v26.7.0, v24.20.0 | 2 | — |
send BoundSocket via subprocess.send | v26.10.0, v24.22.0 | 2 | — |
BlockList addCIDR[s], remove*, PRIVATE_RANGES, size, clear | v26.8.0, v24.21.0 | 2 | — |
setKeepAlive({ interval, count }), dgram bindSync/connectSync | v26.4.0, v24.19.0 | 2 | — |
set/getTypeOfService, typeOfService | v25.6.0, v24.15.0 | 2 | — |
TLS certificateCompression | v26.4.0, v24.19.0 | 2 | — |
tlsSocket.socket | v27.0.0 | 2 | — |
http.isValidHeaderName/Value / websocketMask/Unmask | v26.11.0 / v26.12.0 | 2 | — |
message.signal | v26.1.0, v24.16.0 (fixed v26.7.0, v24.20.0) | 2 | — |
writeInformation (http, http2) | v26.2.0, v24.18.0 | 2 | — |
httpValidation / optimizeEmptyRequests | v26.3.0, v24.19.0 / v25.1.0, v24.12.0 | 2 | — |
setGlobalProxyFromEnv / env proxy | v25.4.0, v24.14.0 / v24.5.0, v22.21.0 | 1.1 | --use-env-proxy |
http2 http1Options, strictSingleValueFields / connectionWindowSize | v25.7.0, v24.15.0 / v26.11.0 | 2 | — |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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.keepAliveTimeoutis 65000 from v27 (was 5000). Set it explicitly behind a load balancer.'upgrade'with a body (v26+): the body is parsed ontoreq, andhead/stream hold only the bytes after it. On v24 the body leaks intohead.dns.reverse(v27+) always sends a PTR query and ignores/etc/hosts. Usedns.lookupService(ip, port)for hosts-aware names.
Pitfalls
check()defaults to'ipv4', socheck('::1')is false. Pass the family.optimizeEmptyRequests: no'end'on bodyless requests (once(req, 'end')hangs);for awaitworks.req.signalon 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
fetchviaHTTP_PROXYuses CONNECT even forhttp://.
Don't
- Don't use
get-portorlisten(0)races (BoundSocket),ip-range-check,bufferutil,global-agent/proxy-agent, orreq.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
| Feature | Versions | Stability | Flag |
|---|---|---|---|
| Permission model, fs grants | v20.0.0 (stable v23.5.0, v22.13.0) | 2 | --permission, --allow-fs-read/write |
| child, worker / addons / wasi | v20.0.0 / v21.6.0, v20.12.0 / v22.3.0, v20.16.0 | 1.1 | --allow-child-process etc. |
| Inspector gate | v25.0.0, v24.12.0 | 1.0 | --allow-inspector |
| Audit mode | v25.8.0, v24.20.0 | - | --permission-audit |
process.permission.drop() | v26.3.0, v24.20.0 | 1.1 | - |
| OpenSSL STORE gate | v26.7.0, v24.21.0 | 1.1 | --allow-openssl-store |
| Network gate | v25.0.0 (not v24) | 1.1 | --allow-net |
| FFI / VFS mount gate | v26.1.0 / v26.9.0 (not v24) | 1.1 | --allow-ffi / --allow-fs-vfs |
| Env var filtering | v27.0.0 (not v24/v26) | 1.1 | --allow-env |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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()anddrop()with an unknown scope returnfalse/ do nothing, with no error. On v24,has('net')isfalseeven 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-processcan escape the model; children inherit flags viaNODE_OPTIONS.--allow-openssl-storeand--allow-ffiaccess is not checked againstfs.read.- Don't pass both
--permissionand--permission-audit: v26.13.0 audits only.
Don't
--experimental-permission(bad option on v24+);vm/vm2as a sandbox; comma-separated--allow-fs-*paths; hand-scrubbingprocess.envon v27+ (use--allow-env).
Reference
- rules/scopes.md: each flag, what it gates, path/wildcard rules, errors, warnings, versions.
- rules/runtime-api.md:
has()/drop()semantics and audit channels/messages. - rules/propagation-and-config.md: child/worker inheritance,
--allow-envdetails, config file,npx.
--process-timeout
| Feature | Versions | Stability | Flag |
|---|---|---|---|
--process-timeout=duration (exit code 124) | v26.11.0 (not on v24) | 1.1 Active development | itself |
--report-on-process-timeout | v26.11.0 | 1.1 | needs --process-timeout |
subprocess.timedOut, error.timedOut (exec/execFile callback) | v27.0.0-alpha.0.1.0 (YAML); absent in v26.13.0 | 2 | none |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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 givenprocess.execArgv) inherit the flag and time out on their own clock, measured from their own start.spawn(process.execPath, …)withoutexecArgvdoes 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 --testpasses 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 asProcessWrap (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,--runor--build-snapshot.inspector.open()throwsERR_INSPECTOR_NOT_AVAILABLE. 'exit'/'beforeExit'handlers don't run. Coverage (NODE_V8_COVERAGE) and--cpu-profoutput 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.timedOutbelongs to thetimeoutoption of spawn/exec/execFile/fork, not to this flag. For sync APIs, checkerr.code === 'ETIMEDOUT'.
Don't
- Don't wrap the command in
timeout 600 node …or writesetTimeout(() => process.exit(1), …).unref()watchdogs. On 26.11+ the flag gives the same exit code plus a diagnosis. - Don't install
why-is-node-runningorwtfnodejust to list open handles.--process-timeoutprints them. - Don't use
--test-timeoutfor "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
| Feature | Versions | Stability | Flag |
|---|---|---|---|
node:quic core (connect, listen, endpoint/session/stream) | v23.8.0 | 1.0 | --experimental-quic (flag added v25.0.0, v24.16.0) |
QUIC alpn/sni options | v26.1.0, v24.16.0 | 1.0 | same |
session.opened, stream.writer/setBody/async iteration, HTTP/3 | v26.2.0, v24.20.0 | 1.0 | same |
node:dtls listen/connect, PSK, SNI | v26.9.0 | 1.1 | --experimental-dtls |
dtls.createSecureContext, session.session/reused/authorized | v26.10.0 | 1.1 | same |
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-checkskill's probe (ornode --versionplus 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) carriesQuicSessions (TLS 1.3), which carryQuicStreams. Events are callback properties (onstream,onerror).openedandclosedare promises. - DTLS: a
DTLSEndpointcarriesDTLSSessions 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'. Setalpnon both sides for a raw protocol. The server needssni(use'*'as the fallback). - QUIC
verifyPeer: 'auto'rejects self-signed certs withoutca.'manual'exposesvalidationErrorCode(a string). - Read every QUIC stream to the end, or
Stream.dump()it. A stream takes abodyor thewriter, not both. dtls.connecttakes an IP literal (no DNS).sendis at most 16384 B and throws beforeopened.- A wrong DTLS PSK or no common cipher makes the handshake go silent. Set
handshakeTimeout(default 60 s). - Both need
--allow-netunder--permission.
Don't
- Don't assume
node:quic/node:dtlsexist because the version is new enough. Checkprocess.configand tell the user if a custom build is needed. - Don't promise HTTP/3
fetch().node:quicis 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)
| Feature | Versions | Stability | Flag |
|---|---|---|---|
module, DatabaseSync/StatementSync | v22.5.0; unflagged v23.4.0, v22.13.0 | 1.2 RC (v25.7.0, v24.15.0) | none |
createTagStore, SQLTagStore | v24.9.0 | 1.2 | none |
setAuthorizer | v24.10.0 | 1.2 | none |
defensive, enableDefensive | v25.1.0, v24.12.0; on by default v25.5.0, v24.14.0 | 1.2 | none |
database.limits | v25.8.0, v24.15.0 | 1.2 | none |
serialize, deserialize | v26.1.0, v24.16.0 | 1.2 | none |
bind boolean, ArrayBuffer | v26.8.0, v24.21.0 | 1.2 | none |
statement.close, statement[Symbol.dispose] | v26.8.0, v24.22.0 | 1.2 | none |
'sqlite.db.query' channel | v26.8.0, v24.22.0 | 1 | none |
stat, resetStats, prepare({ persistent }) | v26.8.0 (not v24) | 1.2 | none |
bind undefined as NULL | v26.10.0 (not v24) | 1.2 | none |
Database/Statement names, createModule | v26.11.0 (not v24) | 1.2 | none |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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
ArrayBuffersilently binds NULL. PassBigInt(flag)andnew Uint8Array(ab)instead. - Before v26.10, an anonymous
undefinedparameter throws. Usenull. - Never put
?in tag-store SQL. v24.22+ and v26 throwERR_INVALID_ARG_VALUE, while v24.19 silently binds NULL. - Defensive mode blocks
writable_schemaedits. 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/sqlite3whennode:sqlitecovers 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
DatabaseSyncin 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)
| Feature | Versions | Stability | Flag |
|---|---|---|---|
node:stream/iter | v25.9.0, v24.20.0 | 1 | --experimental-stream-iter |
filehandle.pull, pullSync, writer | v25.9.0, v24.20.0 | 1 | same |
node:zlib/iter (compress*/decompress*, *Sync) | v25.9.0, v24.20.0 (the docs list only v25.9.0) | 1 | same |
from/toReadable, from/toWritable, Readable[Symbol.for('Stream.toAsyncStreamable')] | v26.1.0, v24.20.0 | 1 | same |
dump, dumpSync | v26.12.0 (not v24) | 1 | same |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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
AsyncIterableorIterableof batches (Uint8Array[]). Strings become UTF-8 bytes. - A transform is
(chunks | null) => chunks(nullmeans flush) or{ transform: async function* (source) {} }. pull()is lazy, so the consumer sets the pace.push()returns{ writer, readable }with a bytebudget.- 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
budgetbelow 16384 throws, andpull()with a pre-aborted signal throws synchronously (rules/versions.md). - Under
'strict', an unawaitedwrite()rejects withERR_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 theFileHandleyourself.
Don't
- Don't subclass
Transformhere. Write a function or generator transform. - Don't use
zlib.createGzip()in a pipeline. UsecompressGzip()fromnode:zlib/iter.
Reference
- rules/sources.md:
from/fromSyncinput rules, filehandlepull/pullSync/writeroptions - rules/pipelines.md:
pull,pipeTo[Sync], transform contracts,node:zlib/iteroptions - rules/push-duplex.md:
push, the Writer interface, backpressure policies,duplex,ondrain - rules/consumers.md: consumers,
tap,merge,broadcast,share - rules/interop.md: classic and web stream adapters, protocol symbols
- rules/versions.md: v24 versus v26.12+ differences
node:test: what is new since v24
| Feature | Versions | Stability | Flag |
|---|---|---|---|
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.0 | 1.0 | --test-randomize, --test-random-seed=<n> |
| Rerun failed only | v24.7.0 | 2 | --test-rerun-failures=<file> |
| Global setup/teardown | v24.0.0 | 1.0 | --test-global-setup=<module> |
expectFailure | v25.5.0, v24.14.0 | 2 | |
t.workerId | v25.8.0, v24.15.0 | 2 | |
t.attempt | v25.0.0 ² | 2 | |
node.test tracing channel | v26.1.0, v24.16.0 | 2 | |
getTestContext() | v26.1.0, v24.19.0 | 2 | |
t.log(), 'test:log' | v26.6.0, v24.20.0 | 2 | |
run({ env }) | v25.6.0, v24.14.0 | 2 | |
| Include never-loaded files | v26.7.0 | 1 | --test-coverage-include-all |
t.assert.called, callCount, nthCalledWith, lastCalledWith | v26.12.0 | 2 | |
mock.mockReturnValue & co. | v27.0.0 | 2 | |
Forbid .only | v27.0.0 | 2 | --test-forbid-only |
| Watch mode Stable | v27.0.0 | 2 | --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-checkskill's probe (ornode --versionplus 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-failuresor--watch. Awaiting subtests one at a time keeps declaration order. run({ env })replacesprocess.envfor children (evenPATH) and throws withisolation: 'none'.- Rerun state is keyed by
file:line:column: moving a test resets it. - Unknown flags fail with
bad option; unknownrun()options (forbidOnlyon 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
- rules/selection-and-ci.md: tags, random order, reruns, forbid-only, global setup.
- rules/context-and-observability.md:
t.log,getTestContext,workerId, tracing/OpenTelemetry. - rules/mocks-and-expectations.md: mock helpers,
t.assert.*,expectFailure. - rules/run-api.md: new
run()options, coverage.
Utilities since v24
| Feature | Versions | Stability | Flag |
|---|---|---|---|
util.debounce, throttle, markPromiseAsHandled | v26.10.0, v24.22.0 | 2 | |
util.isPartialDeepStrictEqual, Buffer.stringLength, isLatin1 | v26.11.0 | 2 | |
util.convertProcessSignalToExitCode; streamConsumers.bytes | v25.4.0; v25.6.0; both v24.14.0 | 2 | |
styleText('#rrggbb'), glob({ followSymlinks }) | v26.1.0, v24.16.0 | 2 | |
fs.mkdtempDisposable[Sync] | v24.4.0 | 2 | |
fs.mkstemp[Sync] | v27.0.0 | 1 | |
fs.Utf8Stream | v24.6.0 | 1 | |
glob({ maxDepth }); fs.openAsBlobSync | v26.9.0; v26.10.0 | 2 | |
async stat({ throwIfNoEntry }) | v25.7.0 (also v24.19.0) | 2 | |
stat/lstat signal; allocUnsafe(n, alignment) | v26.8.0 | 2 | |
Stats *Instant (Temporal) | v26.2.0 | 2 | |
blob.textStream(), ReadableStreamTee | v26.5.0, v24.19.0 | 2, 1 | |
URLPattern global | v24.0.0 | 1 | |
navigator.locks, worker_threads.locks | v24.5.0 | 1 | |
ErrorEvent; QuotaExceededError | v25.0.0; v26.0.0 | 2 | |
Global Web Worker | v26.9.0, default-on in main | 1 | --experimental-web-worker |
process.addUncaughtExceptionCaptureCallback | v25.9.0 | 1 | |
process.ref/unref Stable | v26.11.0 (added v23.6.0, v22.14.0) | 2 | |
tty setRawMode('raw'|'io'), rawMode | v26.8.0, v24.21.0 | 2 | |
stream.compose Stable | v26.2.0, v24.19.0 | 2 | |
assert.Assert; skipPrototype | v24.6.0, v22.19.0; v24.9.0 | 2 |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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.usingonfs.Utf8Streamcallsdestroy()and drops buffered data. Callend().- Locks are per process. A queued request does not keep a worker alive.
new Worker('./w.js')resolves againstcwd; pass aURL.
Don't
lodash.debounce/throttle,p-throttle→util.debounce/throttle.tmp/tmp-promise→mkdtempDisposable/mkstemp;sonic-boom→Utf8Stream.urlpattern-polyfill→URLPattern; in-processasync-mutex→navigator.locks(notproper-lockfile: cross-process).chalk.hex()→styleText('#hex');128 + signals[s]→convertProcessSignalToExitCode.
Reference
- rules/util.md: debounce/throttle options, other util.
- rules/fs.md: temp files, Utf8Stream, glob, stat.
- rules/buffer-and-streams.md: Buffer, web streams.
- rules/globals-and-workers.md: URLPattern, locks, Web Worker.
- rules/process-tty-assert.md: process, tty,
Assert.
node:vfs and VFS-backed single executables
| Feature | Versions | Stability | Flag |
|---|---|---|---|
node:vfs: create, MemoryProvider, RealFSProvider | v26.4.0 | 1 | 26.x: --experimental-vfs; v27+: none (--no-experimental-vfs disables) |
mount/unmount/mountPointURL, ZipProvider, --allow-fs-vfs | v26.9.0 | 1 / 1.1 | as above |
registerProvider, --vfs-load | v26.10.0 | 1 | as above |
vfsBase() · ComposableProvider | v26.11.0 · v26.12.0 | 1 | as above |
--build-sea | v25.5.0 | 1.1 | none |
SEA "useVfs", "vfsArchive" | v26.9.0 | 1.0 | none |
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-checkskill's probe (ornode --versionplus 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 untilunmount(). - The mount is in-process: child processes,
fs.glob, andfs.cpdon't see it. Copying to the real fs fails withEXDEV. --permissionmakesmount()throwERR_INVALID_STATEwithout--allow-fs-vfs.- Not a sandbox:
RealFSProviderreads follow symlinks outside its root. --vfs-loadis rejected inNODE_OPTIONS. SEA:useVfsexcludesuseSnapshot;useCodeCache+useVfsneeds v27+;vfsArchiveneedsuseVfsand excludesassets.- With
vfsArchive,sea.getAsset()can't read the files. Use fs.
Don't
- Don't add
memfs/mock-fs/unionfswhere VFS fits (26.4+). Keep them for v24 and for faking fixed absolute paths. - Don't use
postjector--experimental-sea-configon 25.5+; use--build-sea. - Don't write SEA assets to a temp dir to
requirethem; useuseVfs.
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-seaconfig: every field,useVfs/vfsArchive/code cache, workers, and validation errors. - rules/flags-security.md: read for flags per version,
--vfs-loaddetails, the permission model, and security limits.
ZIP archives in node:zlib
| Feature | Versions | Stability | Flag |
|---|---|---|---|
ZipFile, ZipBuffer, ZipEntry, zipFiles, createZipArchive[Sync], get/setMaxZipContentSize | v26.8.0 (not v24, not v25) | 1.0 Early development | none |
zipEntry.rawContent() method, rawContentSync, rawContentIterator | v27.0.0-alpha.0.0.0 (on v26.x rawContent is a getter) | 1.0 | none |
zlib.crc32c | v27.0.0-alpha.0.0.0 | 2 (zlib) | none |
Experimental API. Before relying on these details, run the
node-experimental-checkskill's probe (ornode --versionplus 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()usesgetMaxZipContentSize()(256 MiB) as its cap.contentIterator()/stream()have no cap unless you passmaxSize.- 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. ZipBufferis a zero-copy view, so don't mutate its source.createZipArchivekeeps duplicate names.- After
close(), entry reads throwERR_INVALID_STATE.
Don't
- Don't add
adm-zip,jszip,archiver,yauzl, orunzipperon 26.8+. On v24, a package is still needed. - Don't use
zlib.gzipto make a ".zip". Gzip is not the ZIP format. - For gzip/zstd/brotli transforms in iterable pipelines, see the
node-stream-iterskill.
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