nodejs-map 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +95 -2
- package/dist/app/assets/app.worker-PoneE3J2.js +8 -0
- package/dist/app/assets/app.worker-PoneE3J2.js.map +1 -0
- package/dist/app/assets/atlas.worker-B0xwOHwo.js +2 -0
- package/dist/app/assets/atlas.worker-B0xwOHwo.js.map +1 -0
- package/dist/app/assets/cm-BiB0hvWw.js +13 -0
- package/dist/app/assets/cm-BiB0hvWw.js.map +1 -0
- package/dist/app/assets/dist-B37Ex44M.js +2 -0
- package/dist/app/assets/dist-B37Ex44M.js.map +1 -0
- package/dist/app/assets/dist-hDhUT_Vg.js +2 -0
- package/dist/app/assets/dist-hDhUT_Vg.js.map +1 -0
- package/dist/app/assets/index-2K-ozYKf.js +16 -0
- package/dist/app/assets/index-2K-ozYKf.js.map +1 -0
- package/dist/app/assets/index-Cw18rDSZ.css +1 -0
- package/dist/app/assets/map-Cnxgv4Ve.js +129 -0
- package/dist/app/assets/map-Cnxgv4Ve.js.map +1 -0
- package/dist/app/assets/map-Cz4s03Wm.css +1 -0
- package/dist/app/assets/sdf-label-font-1nAa0TP8.png +0 -0
- package/dist/app/config.json +5 -0
- package/dist/app/favicon.svg +1 -0
- package/dist/app/index.html +21 -0
- package/dist/atlas/v26.13.1/build-report.json +178 -0
- package/dist/atlas/v26.13.1/chunks/lib.bootstrap.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.core.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.crypto.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.devtools.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.events.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.fs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.modules.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.net.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.net.1.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.platform.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.process.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.rest.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.streams.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.timers.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.workers.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.zlib.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.callbacks.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.crypto.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.diag.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.fs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.inspector.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.loop.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.modules.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.napi.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.net.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.net.1.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.process.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.rest.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.support.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.zlib.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.api.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.backends.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.fs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.loop.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.net.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.rest.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.threadpool.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.api.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.asmjs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.ast.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.base.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.baseline.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.bigint.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.builtins.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.codegen.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.codegen.riscv.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.common.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler-dispatcher.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler.backend.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler.turboshaft.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.d8.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.date.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.debug.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.deoptimizer.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.diagnostics.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.dumpling.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.execution.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.extensions.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.flags.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.fuzzilli.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.handles.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.heap.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.heap.cppgc.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.ic.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.init.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.inspector.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.interpreter.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.json.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.libplatform.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.libsampler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.logging.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.maglev.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.numbers.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.objects.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.parsing.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.profiler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.regexp.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.root.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.roots.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.runtime.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.sandbox.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.snapshot.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.strings.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.tasks.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.torque.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.tracing.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.trap-handler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.utils.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.wasm.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.zone.0.json +1 -0
- package/dist/atlas/v26.13.1/edges.json +1 -0
- package/dist/atlas/v26.13.1/files.json +1 -0
- package/dist/atlas/v26.13.1/index.json +1 -0
- package/dist/atlas/v26.13.1/link-check.json +16 -0
- package/dist/atlas/v26.13.1/search.json +1 -0
- package/dist/cli.js +6002 -0
- package/dist/examples.json +1 -0
- package/dist/lessons/async-await-chain.nmrec.gz +0 -0
- package/dist/lessons/beforeexit-and-exit.nmrec.gz +0 -0
- package/dist/lessons/dns-lookup-thread-pool.nmrec.gz +0 -0
- package/dist/lessons/esm-twist.nmrec.gz +0 -0
- package/dist/lessons/eventemitter-is-synchronous.nmrec.gz +0 -0
- package/dist/lessons/fs-promises-await.nmrec.gz +0 -0
- package/dist/lessons/fs-sync-vs-async.nmrec.gz +0 -0
- package/dist/lessons/index.json +621 -0
- package/dist/lessons/interval-and-clear.nmrec.gz +0 -0
- package/dist/lessons/nested-ticks-and-microtasks.nmrec.gz +0 -0
- package/dist/lessons/pbkdf2-six-jobs-four-threads.nmrec.gz +0 -0
- package/dist/lessons/pool-with-two-threads.nmrec.gz +0 -0
- package/dist/lessons/readfile-thread-pool.nmrec.gz +0 -0
- package/dist/lessons/tcp-round-trip.nmrec.gz +0 -0
- package/dist/lessons/tick-before-promise.nmrec.gz +0 -0
- package/dist/lessons/timeout-vs-immediate-io.nmrec.gz +0 -0
- package/dist/lessons/timeout-vs-immediate-main.nmrec.gz +0 -0
- package/dist/lessons/timer-vs-file-read.nmrec.gz +0 -0
- package/dist/lessons/timers-phase.nmrec.gz +0 -0
- package/dist/preload.cjs +477 -0
- package/package.json +25 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"examples":[{"id":"tick-vs-promise","title":"nextTick vs promise vs queueMicrotask (CommonJS)","summary":"NextTick queue runs before the microtask queue after the main script; promise reactions and queueMicrotask share one queue, FIFO; timers come after both. Compare esm-tick-vs-promise.mjs: the order of tick and promise flips in an ES module.","module":"commonjs","text":"// Shows: process.nextTick vs promise reactions vs queueMicrotask, at the top\n// level of a CommonJS main script.\n// Why: when the main script returns, Node drains the nextTick queue first and\n// then runs V8's microtask queue. Promise reactions and queueMicrotask\n// callbacks share that one microtask queue, so they run in the order they\n// were queued. Only after both are empty does the event loop start, so the\n// timer comes last. (An ES module differs: see esm-tick-vs-promise.mjs.)\nconsole.log('1 sync start');\nsetTimeout(() => console.log('6 timeout 0'), 0);\nPromise.resolve().then(() => console.log('4 promise then'));\nqueueMicrotask(() => console.log('5 queueMicrotask'));\nprocess.nextTick(() => console.log('3 nextTick'));\nconsole.log('2 sync end');\n","racy":false},{"id":"microtask-nesting","title":"Ticks queued from microtasks and the reverse","summary":"Tick queue is drained fully (including new ticks) before microtasks run; microtasks queued while draining run in the same drain; a tick queued from a microtask waits for the microtask queue to empty.","module":"commonjs","text":"// Shows: nesting of nextTick and microtasks (a tick queued from a microtask,\n// and a microtask queued from a tick).\n// Why: after a callback Node runs \"tick, then microtasks\" in a loop:\n// do { run every queued tick (including ticks queued meanwhile);\n// drain the microtask queue completely (including microtasks queued\n// meanwhile) } while (more ticks exist).\n// So tick D, queued by tick A, still runs before any promise job. Promise C,\n// queued by tick A, goes behind B in the microtask queue. Tick E, queued by\n// microtask B, must wait until the microtask queue is empty (after C and F).\nconsole.log('sync start');\nprocess.nextTick(() => {\n console.log('tick A');\n Promise.resolve().then(() => console.log('promise C (queued by tick A)'));\n process.nextTick(() => console.log('tick D (queued by tick A)'));\n});\nPromise.resolve().then(() => {\n console.log('promise B');\n process.nextTick(() => console.log('tick E (queued by promise B)'));\n queueMicrotask(() => console.log('microtask F (queued by promise B)'));\n});\nconsole.log('sync end');\n","racy":false},{"id":"esm-tick-vs-promise","title":"nextTick vs promise at ES module top level","summary":"An ES module body runs inside a promise job, so promise reactions beat nextTick. The only program where tick and promise order differs from CommonJS.","module":"esm","text":"// Shows: the nextTick-vs-promise order at the top level of an ES module.\n// Why: an ES module is evaluated from inside a promise job (the module\n// loader is promise based), so we are already running as a microtask when\n// the module body returns. V8 keeps draining the microtask queue before\n// control returns to Node's nextTick processing, so the promise reaction runs\n// BEFORE the nextTick callback. In CommonJS (tick-vs-promise.js) it is the\n// other way round.\nconsole.log('1 sync start');\nprocess.nextTick(() => console.log('4 nextTick'));\nPromise.resolve().then(() => console.log('3 promise then'));\nconsole.log('2 sync end');\n","racy":false},{"id":"esm-top-level-await","title":"Top-level await","summary":"Await suspends the module while ticks and timers run; continuation runs as a microtask after the resolving timer callback.","module":"esm","text":"// Shows: top-level await in an ES module. Code after the await is a promise\n// continuation, so it runs only once the awaited promise settles, and the\n// event loop keeps running other work (ticks, timers) in the meantime.\n// Why: `await` suspends the module body. The nextTick callback and the 5 ms\n// timer run while it is suspended; the 20 ms timer resolves the awaited\n// promise, and the continuation runs as a microtask right after that timer\n// callback.\nconsole.log('module start');\nprocess.nextTick(() => console.log('nextTick while suspended'));\nsetTimeout(() => console.log('timeout 5ms'), 5);\nawait new Promise((resolve) =>\n setTimeout(() => {\n console.log('timeout 20ms resolves the awaited promise');\n resolve();\n }, 20)\n);\nconsole.log('after await');\n","racy":false},{"id":"timeout-vs-immediate-main","title":"setTimeout(0) vs setImmediate from the main script","summary":"SetTimeout 0 is 1 ms; first loop iteration: timers phase then check phase; order depends on whether 1 ms has passed. Classic race from the Node docs.","module":"commonjs","text":"// Shows: setTimeout(fn, 0) vs setImmediate(fn) called from the main script.\n// RACY. The order depends on timing, not on a rule.\n// Why: a delay of 0 is stored as 1 ms. The first loop iteration runs the\n// timers phase first, and a timer is due only if at least 1 ms has passed\n// (by the loop's clock) since it was scheduled. If the process took more than\n// 1 ms between scheduling the timer and the first timers check, \"timeout\"\n// prints first; otherwise the check phase runs \"immediate\" first and the\n// timer waits for the next iteration. Machine load changes which one wins.\nsetTimeout(() => console.log('timeout 0'), 0);\nsetImmediate(() => console.log('immediate'));\n","racy":true},{"id":"timeout-vs-immediate-io","title":"setTimeout(0) vs setImmediate inside an I/O callback","summary":"Poll phase is followed by check phase, then timers on the next iteration.","module":"commonjs","text":"// Shows: setTimeout(fn, 0) vs setImmediate(fn) called from inside an I/O\n// callback. Deterministic: \"immediate\" always comes first.\n// Why: a file-read callback runs in the poll phase. After poll the loop goes\n// to the check phase (setImmediate callbacks), and only then wraps around to\n// the timers phase of the next iteration. So the immediate runs first no\n// matter how much time has passed.\nconst fs = require('fs');\n\nfs.readFile(__filename, () => {\n console.log('readFile callback');\n setTimeout(() => console.log('timeout 0'), 0);\n setImmediate(() => console.log('immediate'));\n});\n","racy":false},{"id":"timer-order","title":"Timer ordering","summary":"Due time order across delays; creation order for equal delays; delay 0 is treated as 1.","module":"commonjs","text":"// Shows: how timers are ordered. Deterministic in practice.\n// Why: timers fire in order of their due time (start + delay). Timers with\n// the same delay keep the order they were created in. A delay of 0 is\n// treated as 1, so \"E\" (delay 0) behaves like delay 1 and runs after \"D\",\n// which was created first. Creation order does not matter across different\n// delays: the 200 ms timer was created first but fires last.\n// Caveat: with delays of 10 and 1 ms an unlucky run under load printed E after\n// C (1 in 200). Likely explanation, not verified: setTimeout reads the clock,\n// so a pause of more than ~9 ms between two setTimeout calls makes the later\n// short timer due after an earlier longer one. The wide gaps used here make\n// that very unlikely, not impossible (see README).\nsetTimeout(() => console.log('A delay 200'), 200);\nsetTimeout(() => console.log('B delay 100'), 100);\nsetTimeout(() => console.log('C delay 100'), 100);\nsetTimeout(() => console.log('D delay 1'), 1);\nsetTimeout(() => console.log('E delay 0 (same as 1)'), 0);\n","racy":false},{"id":"interval-clear","title":"setInterval and clearInterval","summary":"Interval re-arms until cleared; empty loop lets the process exit.","module":"commonjs","text":"// Shows: setInterval repeating until clearInterval, and that clearing the last\n// timer lets the process exit by itself.\n// Why: an active interval keeps the event loop alive and is re-armed after\n// each run. Calling clearInterval inside its own callback stops it; with no\n// other handles left, the loop is empty, so Node emits 'exit' and ends.\nlet n = 0;\nconst timer = setInterval(() => {\n n += 1;\n console.log('interval run ' + n);\n if (n === 3) {\n clearInterval(timer);\n console.log('interval cleared');\n }\n}, 5);\nprocess.on('exit', () => console.log('exit'));\n","racy":false},{"id":"unref-timer","title":"Unref'd timers","summary":"Unref does not keep the loop alive; an unref'd timer still fires while the loop is alive for other reasons.","module":"commonjs","text":"// Shows: an unref'd timer does not keep the process alive.\n// Why: unref() tells Node not to count the timer as a reason to keep the loop\n// running. The 1000 ms timer never fires: when the last ref'd timer (20 ms)\n// is done, the loop has nothing left that counts and the process exits.\n// The 5 ms unref'd timer does fire, because the ref'd 20 ms timer keeps the\n// loop alive for long enough.\nconst never = setTimeout(() => console.log('unref 1000ms fired (never)'), 1000);\nnever.unref();\nconst early = setTimeout(() => console.log('unref 5ms fired'), 5);\nearly.unref();\nsetTimeout(() => console.log('ref 20ms fired'), 20);\nconsole.log('hasRef: never=' + never.hasRef() + ' early=' + early.hasRef());\nprocess.on('exit', () => console.log('exit'));\n","racy":false},{"id":"timer-vs-readfile-race","title":"A 5 ms timer racing a file read","summary":"Thread pool file I/O vs the clock; why pausing JavaScript changes the order. This is the example in the brief about pausing changing behaviour.","module":"commonjs","text":"// Shows: a 5 ms timer racing a file read. RACY.\n// Why: fs.readFile does its work (open, fstat, read, close) on a thread\n// pool thread as one job and reports back to the event loop when it is\n// done; the timer is checked against the clock. Whichever is ready first at\n// the time the loop looks wins. Normally the small file is read in well under 5 ms (\"file then\n// timer\"). If JavaScript is stopped for longer than that (a breakpoint, a\n// busy machine) the timer is already due and runs first (\"timer then file\").\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\n\nconst dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-map-corpus-'));\nconst file = path.join(dir, 'data.txt');\nfs.writeFileSync(file, 'hello');\n\nlet pending = 2;\nfunction done() {\n if (--pending === 0) fs.rmSync(dir, { recursive: true, force: true });\n}\n\nfs.readFile(file, 'utf8', () => {\n console.log('file read');\n done();\n});\nsetTimeout(() => {\n console.log('timer 5ms');\n done();\n}, 5);\n","racy":true},{"id":"readfile-callback","title":"fs.readFile callback path","summary":"A small readFile is one thread pool job in Node 26; callback comes after the script and its nextTick.","module":"commonjs","text":"// Shows: the callback path of fs.readFile. Deterministic.\n// Why: readFile returns at once. In Node 26 a small file is read as ONE\n// thread pool job: a pool thread opens, stats, reads and closes the file,\n// then hands the result back to the event loop. So the rest of the script\n// runs first, then the nextTick, and the readFile callback comes later,\n// when the loop picks the finished job up. (Its order relative to\n// setImmediate is NOT guaranteed: see readfile-vs-immediate.js.)\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\n\nconst dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-map-corpus-'));\nconst file = path.join(dir, 'data.txt');\nfs.writeFileSync(file, 'hello world');\n\nfs.readFile(file, 'utf8', (err, text) => {\n console.log('readFile callback: err=' + err + ' text=' + text);\n fs.rmSync(dir, { recursive: true, force: true });\n});\nprocess.nextTick(() => console.log('nextTick'));\nconsole.log('sync: after calling readFile');\n","racy":false},{"id":"readfile-vs-immediate","title":"fs.readFile callback vs setImmediate","summary":"Phases: poll (I/O callback) vs check (immediate); a thread pool job can finish before the loop's first poll, and then its callback runs before the first check phase. Platform dependent: on Windows the immediate wins about 99% of runs, in WSL2 Linux the readFile callback wins about 94%. It depends on whether the pool thread finishes before the loop first polls.","module":"commonjs","text":"// Shows: fs.readFile callback vs a setImmediate queued right after it. RACY.\n// What is certain: in Node 26 a small readFile is one thread pool job, and\n// its callback is delivered when the loop polls for finished work (inside\n// the poll phase on Linux and macOS, right after it on Windows). The\n// immediate runs in the check phase, which comes after poll in the same\n// loop turn. So the order depends on one thing: has the pool thread\n// finished the read by the time the loop first polls?\n// What was observed on Node 26.13.1: on Windows the immediate came first in\n// about 99% of runs; on Linux (WSL2) the readFile callback came first in\n// about 94% of runs (the read usually finishes before the first poll\n// there). Treat the order as unspecified.\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\n\nconst dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-map-corpus-'));\nconst file = path.join(dir, 'data.txt');\nfs.writeFileSync(file, 'hello world');\n\nlet pending = 2;\nfunction done() {\n if (--pending === 0) fs.rmSync(dir, { recursive: true, force: true });\n}\nfs.readFile(file, 'utf8', () => {\n console.log('readFile callback');\n done();\n});\nsetImmediate(() => {\n console.log('setImmediate');\n done();\n});\n","racy":true},{"id":"fs-sync-vs-async","title":"fs sync vs async","summary":"Sync calls block the main thread; callback versions deliver later via the poll phase.","module":"commonjs","text":"// Shows: fs.*Sync blocks and returns the result in place; the callback\n// version returns immediately and delivers the result later.\n// Why: readFileSync runs the whole read on the main thread before the next\n// line. fs.stat hands the work to the thread pool, so the line after it runs\n// first and the callback is delivered from the poll phase of the event loop.\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\n\nconst dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-map-corpus-'));\nconst file = path.join(dir, 'data.txt');\nfs.writeFileSync(file, 'twelve bytes');\n\nconsole.log('sync result: ' + fs.readFileSync(file, 'utf8'));\nfs.stat(file, (err, st) => {\n console.log('async stat callback: size=' + st.size);\n fs.rmSync(dir, { recursive: true, force: true });\n});\nconsole.log('after fs.stat call (callback not run yet)');\n","racy":false},{"id":"fs-promises-await","title":"fs.promises with async/await","summary":"Async functions run synchronously to the first await; continuations are microtasks after the thread pool result arrives.","module":"commonjs","text":"// Shows: fs.promises with async/await. Deterministic.\n// Why: an async function runs synchronously until its first await, so\n// \"main start\" prints before \"sync: after main() call\". Each awaited fs call\n// goes to the thread pool; the function continues as a promise continuation\n// (a microtask) once the loop delivers the result. The nextTick runs before\n// any of that, because the file work cannot finish in the meantime.\nconst fsp = require('fs/promises');\nconst os = require('os');\nconst path = require('path');\n\nasync function main() {\n console.log('main start');\n const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'nodejs-map-corpus-'));\n const file = path.join(dir, 'data.txt');\n await fsp.writeFile(file, 'abc');\n console.log('written');\n const text = await fsp.readFile(file, 'utf8');\n console.log('read: ' + text);\n await fsp.rm(dir, { recursive: true, force: true });\n return 'finished';\n}\n\nmain().then((v) => console.log('main resolved: ' + v));\nprocess.nextTick(() => console.log('nextTick'));\nconsole.log('sync: after main() call');\n","racy":false},{"id":"threadpool-pbkdf2","title":"Thread pool saturation: 6 pbkdf2 jobs on 4 threads","summary":"Default pool of 4 threads; jobs 5 and 6 wait for a free thread. Prints each wave sorted; order inside a wave is not stable and is not printed. Racy only rarely: the wave split changed in about 1% of runs under load (a pool thread descheduled for a long time). classify.mjs removes UV_THREADPOOL_SIZE from the environment of the child.","module":"commonjs","text":"// Shows: thread pool saturation. Six crypto.pbkdf2 jobs, default pool of 4\n// threads (run without UV_THREADPOOL_SIZE set; see threadpool-size.js).\n// Why: all six jobs are queued at once, but only 4 threads exist, so jobs\n// 1-4 start together and jobs 5 and 6 wait until a thread is free. The order\n// inside a wave depends on thread scheduling, so we print each wave sorted;\n// what is stable is WHICH jobs belong to which wave. (Racy only if job 5 or 6\n// were to finish before one of jobs 1-4, which means a thread was starved.)\nconst crypto = require('crypto');\n\nconst done = [];\nfor (let id = 1; id <= 6; id++) {\n crypto.pbkdf2('password', 'salt', 150000, 32, 'sha512', () => {\n done.push(id);\n if (done.length === 4) {\n console.log('wave 1 done: ' + done.slice().sort().join(' '));\n } else if (done.length === 6) {\n console.log('wave 2 done: ' + done.slice(4).sort().join(' '));\n }\n });\n}\nconsole.log('queued 6 jobs');\n","racy":true},{"id":"threadpool-size","title":"Thread pool size 2 set from inside the script","summary":"UV_THREADPOOL_SIZE before first pool use; jobs run in waves of the pool size. Setting process.env.UV_THREADPOOL_SIZE in the script works on Windows and Linux here (see README).","module":"commonjs","text":"// Shows: the thread pool size controls how many jobs run at once.\n// Setting UV_THREADPOOL_SIZE inside the script only works if it is done\n// before the first thread pool use (the pool is created lazily on the first\n// job). Here it is set to 2 before anything else, so 4 jobs run as two waves\n// of 2. To get the same effect from outside, start the process with the\n// variable set: UV_THREADPOOL_SIZE=2 node threadpool-size.js\n// (PowerShell: $env:UV_THREADPOOL_SIZE=2; node threadpool-size.js).\n// Racy only if a job of wave 2 finished before one of wave 1.\nprocess.env.UV_THREADPOOL_SIZE = '2';\nconst crypto = require('crypto');\n\nconst done = [];\nfor (let id = 1; id <= 4; id++) {\n crypto.pbkdf2('password', 'salt', 150000, 32, 'sha512', () => {\n done.push(id);\n if (done.length === 2) console.log('wave 1 done: ' + done.slice().sort().join(' '));\n if (done.length === 4) console.log('wave 2 done: ' + done.slice(2).sort().join(' '));\n });\n}\nconsole.log('queued 4 jobs, pool size set to 2');\n","racy":true},{"id":"zlib-async","title":"zlib on the thread pool vs sync","summary":"Zlib callbacks run on the thread pool; gzipSync blocks.","module":"commonjs","text":"// Shows: zlib's callback API compresses on the thread pool, the *Sync API\n// compresses on the main thread. Deterministic.\n// Why: gzipSync finishes inside the script, before anything asynchronous can\n// be reported. The callback from zlib.gzip is delivered later by the event\n// loop; the gunzip started inside it is delivered later still.\nconst zlib = require('zlib');\n\nconst input = Buffer.alloc(2000, 'a');\n\nzlib.gzip(input, (err, gz) => {\n console.log('gzip callback: smaller=' + (gz.length < input.length));\n zlib.gunzip(gz, (err2, out) => {\n console.log('gunzip callback: roundtrip ok=' + out.equals(input));\n });\n});\nconsole.log('gzip requested');\nconst syncGz = zlib.gzipSync(input);\nconsole.log('gzipSync done: smaller=' + (syncGz.length < input.length));\n","racy":false},{"id":"crypto-randombytes","title":"crypto.randomBytes async vs sync","summary":"Async randomBytes uses the thread pool; callback arrives after nextTick. Random bytes are never printed, only lengths.","module":"commonjs","text":"// Shows: crypto.randomBytes with a callback runs on the thread pool; without\n// a callback it runs synchronously. Deterministic.\n// Why: randomBytesSync returns before the next line. The callback form queues\n// a job for a pool thread and the callback comes from the event loop, after\n// the script and its nextTick work. (Only lengths are printed: the bytes\n// differ on every run.)\nconst crypto = require('crypto');\n\ncrypto.randomBytes(16, (err, buf) => {\n console.log('async randomBytes callback: length=' + buf.length);\n});\nconsole.log('sync randomBytes: length=' + crypto.randomBytes(8).length);\nprocess.nextTick(() => console.log('nextTick'));\nconsole.log('end of script');\n","racy":false},{"id":"dns-lookup","title":"dns.lookup (thread pool, getaddrinfo)","summary":"Dns.lookup is thread pool work; IP literals skip the resolver and call back via nextTick. Only \"localhost\" and an IP literal; no network.","module":"commonjs","text":"// Shows: dns.lookup uses the operating system resolver (getaddrinfo) on the\n// thread pool, so its callback is always asynchronous. Deterministic.\n// Why: an IP literal needs no resolver call, and this case was observed to\n// call back before the thread pool lookup of \"localhost\" returns (see README:\n// verified by output on Node 26.13.1, not by reading lib/dns.js). Nothing\n// here uses the network: \"localhost\" is answered from the local hosts file.\n// Only the type of the address is printed, never its value (127.0.0.1 or ::1\n// depends on the system).\nconst dns = require('dns');\n\ndns.lookup('localhost', (err, address, family) => {\n console.log('lookup localhost callback: err=' + err + ' address is string=' + (typeof address === 'string'));\n});\ndns.lookup('127.0.0.1', (err, address, family) => {\n console.log('lookup 127.0.0.1 callback: address=' + address + ' family=' + family);\n});\nprocess.nextTick(() => console.log('nextTick'));\nconsole.log('sync: both lookups requested');\n","racy":false},{"id":"dns-resolve-local","title":"dns.resolve4 against a local fake DNS server","summary":"Resolve4 uses c-ares and a UDP socket, not the thread pool; a UDP responder on 127.0.0.1 keeps it off the network. Closest safe stand-in for dns.resolve4(\"localhost\"), which would query a real DNS server.","module":"commonjs","text":"// Shows: dns.Resolver#resolve4 does NOT use the thread pool: it speaks DNS\n// itself (c-ares) over a UDP socket that the event loop polls.\n// To stay off the network the \"DNS server\" is a tiny UDP responder on\n// 127.0.0.1 inside this script that answers every A query with 10.1.2.3.\n// Why this order: the query is sent from the event loop and the answer comes\n// back as a socket event, so the callback runs after the script and its tick.\nconst dns = require('dns');\nconst dgram = require('dgram');\n\nconst server = dgram.createSocket('udp4');\nserver.on('message', (msg, rinfo) => {\n let i = 12; // skip the 12-byte header, then walk the question name\n while (msg[i] !== 0) i += msg[i] + 1;\n i += 1 + 4; // terminating zero byte, QTYPE, QCLASS\n const head = Buffer.alloc(12);\n msg.copy(head, 0, 0, 2); // same id\n head.writeUInt16BE(0x8180, 2); // response, recursion desired + available\n head.writeUInt16BE(1, 4); // one question\n head.writeUInt16BE(1, 6); // one answer\n const answer = Buffer.from([0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 10, 1, 2, 3]);\n server.send(Buffer.concat([head, msg.subarray(12, i), answer]), rinfo.port, rinfo.address);\n});\n\nserver.bind(0, '127.0.0.1', () => {\n const resolver = new dns.Resolver({ timeout: 1000, tries: 1 });\n resolver.setServers(['127.0.0.1:' + server.address().port]);\n resolver.resolve4('example.test', (err, addresses) => {\n console.log('resolve4 callback: err=' + err + ' addresses=' + addresses.join(','));\n server.close(() => console.log('responder closed'));\n });\n process.nextTick(() => console.log('nextTick'));\n console.log('sync: resolve4 requested');\n});\n","racy":false},{"id":"async-await-chain","title":"async/await chain","summary":"Async functions run synchronously to the first await; each continuation is a microtask, one per await; a timer-based await resumes from the timers phase.","module":"commonjs","text":"// Shows: where each part of a chain of async functions runs. Deterministic.\n// Why: an async function runs synchronously up to its first await, so the\n// three \"start\" lines print in call order before the script ends. After that\n// every continuation is a microtask: c resumes first, then b once c's\n// promise resolves, then a. The setTimeout(1) inside a is different: a\n// resumes after it from the timers phase, so it comes after the nextTick and\n// all microtasks.\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function c() {\n console.log('c start');\n await null;\n console.log('c resumed (microtask)');\n return 'c-value';\n}\nasync function b() {\n console.log('b start');\n const v = await c();\n console.log('b resumed with ' + v);\n return 'b-value';\n}\nasync function a() {\n console.log('a start');\n const v = await b();\n console.log('a resumed with ' + v);\n await sleep(1);\n console.log('a resumed after timer');\n}\n\na().then(() => console.log('a() promise resolved'));\nprocess.nextTick(() => console.log('nextTick'));\nconsole.log('sync end');\n","racy":false},{"id":"promise-combinators","title":"Promise.all, allSettled, race and rejection handling","summary":"Combinators settle on a timer callback then a microtask; handlers attached in time avoid unhandled rejections.","module":"commonjs","text":"// Shows: when Promise.all, Promise.allSettled and Promise.race settle, and\n// ordering of rejection handling. Deterministic, and safe: every promise that\n// can reject has a handler attached before it rejects, so no\n// unhandled-rejection warning or crash happens.\n// Why: the timers have different delays (30, 90, 150, 210 ms), so they fire in\n// delay order; each combinator settles as soon as its rule is met (all: last\n// input fulfils or first input rejects; race: first input settles) and its\n// handler runs as a microtask right after that timer callback.\nconst later = (ms, value, fail) =>\n new Promise((resolve, reject) =>\n setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms)\n );\n\nPromise.race([later(90, 'slow'), later(30, 'fast')]).then((v) => console.log('race winner: ' + v));\nPromise.all([later(150, 'a'), later(90, 'b')]).then((v) => console.log('all fulfilled: ' + v.join(',')));\nPromise.all([later(210, 'ok'), later(30, 'boom', true)]).catch((e) =>\n console.log('all rejected early: ' + e.message)\n);\nPromise.allSettled([later(150, 'x'), later(30, 'y', true)]).then((r) =>\n console.log('allSettled: ' + r.map((s) => s.status).join(','))\n);\n\nconst p = Promise.reject(new Error('handled in same tick'));\np.catch((e) => console.log('catch: ' + e.message)).then(() => console.log('then after catch'));\nconsole.log('sync end');\n","racy":false},{"id":"eventemitter-sync","title":"EventEmitter is synchronous","summary":"Emit calls listeners in order before returning; deferring needs nextTick or setImmediate.","module":"commonjs","text":"// Shows: EventEmitter#emit is synchronous. Deterministic.\n// Why: emit() calls every listener, in the order they were added, before it\n// returns; there is no queue and no event loop turn involved. A listener added\n// with once() is removed after its first call. To make listeners run later,\n// the caller must defer the emit itself, for example with process.nextTick\n// (runs after the current script) or setImmediate (runs in the check phase).\nconst { EventEmitter } = require('events');\n\nconst emitter = new EventEmitter();\nemitter.on('ping', () => console.log('listener 1'));\nemitter.once('ping', () => console.log('listener 2 (once)'));\nemitter.on('ping', () => console.log('listener 3'));\n\nconsole.log('before emit');\nemitter.emit('ping');\nconsole.log('after emit (all listeners already ran)');\n\nprocess.nextTick(() => {\n console.log('nextTick: emit again');\n emitter.emit('ping');\n});\nsetImmediate(() => {\n console.log('setImmediate: emit again');\n emitter.emit('ping');\n});\n","racy":false},{"id":"beforeexit-exit","title":"beforeExit and exit","summary":"BeforeExit can schedule more work and is emitted again; exit allows only synchronous work.","module":"commonjs","text":"// Shows: process 'beforeExit' vs 'exit'. Deterministic.\n// Why: when the event loop has nothing left, Node emits 'beforeExit'. A\n// listener may schedule more work, which restarts the loop; 'beforeExit' is\n// emitted again when that work is done. 'exit' is emitted last, once, and\n// only synchronous code can run in it: the timer scheduled there never fires.\nlet beforeExitCount = 0;\nprocess.on('beforeExit', (code) => {\n beforeExitCount += 1;\n console.log('beforeExit #' + beforeExitCount + ' code=' + code);\n if (beforeExitCount === 1) {\n setTimeout(() => console.log('timer scheduled from beforeExit'), 1);\n }\n});\nprocess.on('exit', (code) => {\n console.log('exit code=' + code);\n setTimeout(() => console.log('never printed'), 0);\n});\nsetTimeout(() => console.log('main timer'), 1);\nconsole.log('sync end');\n","racy":false},{"id":"net-roundtrip","title":"TCP server and client on 127.0.0.1","summary":"Socket I/O is delivered in the poll phase; clean shutdown of server and client. Only causally ordered lines are printed.","module":"commonjs","text":"// Shows: a TCP server and client talking over 127.0.0.1 on an OS-chosen port\n// (port 0), then both closing so the process exits by itself.\n// Why this order: every printed line is caused by the one before it\n// (listening -> connection -> data -> reply -> close), so the order is fixed\n// by the protocol. Lines that would be unordered (the client's 'connect' vs\n// the server's 'connection', the two sides' 'close') are deliberately not\n// printed. The port number varies and is not printed.\nconst net = require('net');\n\nconst server = net.createServer((socket) => {\n console.log('server: connection');\n socket.on('data', (chunk) => {\n console.log('server: got ' + chunk.toString());\n socket.end('pong');\n });\n});\n\nserver.listen(0, '127.0.0.1', () => {\n console.log('server: listening');\n const client = net.connect(server.address().port, '127.0.0.1', () => client.write('ping'));\n client.on('data', (chunk) => console.log('client: got ' + chunk.toString()));\n client.on('close', () => {\n console.log('client: closed');\n server.close(() => console.log('server: closed'));\n });\n});\n","racy":false},{"id":"http-roundtrip","title":"HTTP server and one request","summary":"Http builds on net sockets; closing the server after the response ends the process.","module":"commonjs","text":"// Shows: a local HTTP server and one request to it, closing cleanly.\n// Why this order: the request cannot be sent before the server is listening,\n// the server's handler runs before the client sees a response, and the body\n// 'end' comes after its data. The server is closed only after the response\n// is fully read; the request asks for \"Connection: close\" so no keep-alive\n// socket holds the process open. Port numbers vary and are not printed.\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n console.log('server: ' + req.method + ' ' + req.url);\n res.end('hello');\n});\n\nserver.listen(0, '127.0.0.1', () => {\n console.log('server: listening');\n const req = http.get(\n { host: '127.0.0.1', port: server.address().port, path: '/hi', headers: { Connection: 'close' } },\n (res) => {\n console.log('client: status ' + res.statusCode);\n let body = '';\n res.on('data', (chunk) => (body += chunk));\n res.on('end', () => {\n console.log('client: body ' + body);\n server.close(() => console.log('server: closed'));\n });\n }\n );\n req.on('error', (err) => console.log('client: error ' + err.code));\n});\n","racy":false},{"id":"streams-memory","title":"Readable to Transform to Writable","summary":"Stream.pipeline moves one chunk at a time; backpressure interleaves read, transform and write. Order is stable by observation, not guaranteed by a specification.","module":"commonjs","text":"// Shows: a small Readable -> Transform -> Writable pipeline in memory.\n// Why this order: stream.pipeline moves one chunk at a time and respects\n// backpressure. Each chunk is read, transformed, then written before the next\n// is pulled, and 'finish' fires after the last write. No I/O is involved, so\n// everything runs from promise and nextTick queues; the order was observed to\n// be stable over many runs (see README) rather than guaranteed by a spec.\nconst { Readable, Transform, Writable, pipeline } = require('stream');\n\nconst source = Readable.from(['a', 'b', 'c']);\nconst upper = new Transform({\n transform(chunk, enc, cb) {\n console.log('transform ' + chunk);\n cb(null, chunk.toString().toUpperCase());\n },\n});\nconst sink = new Writable({\n write(chunk, enc, cb) {\n console.log('write ' + chunk);\n cb();\n },\n});\n\npipeline(source, upper, sink, (err) => console.log('pipeline done: err=' + err));\nconsole.log('sync: pipeline started');\n","racy":false},{"id":"stream-pipeline-file","title":"stream.pipeline with files in os.tmpdir()","summary":"File streams use the thread pool; pipeline calls back once, after the last stream has closed. Temp directory is removed at the end.","module":"commonjs","text":"// Shows: stream.pipeline with real files: createReadStream -> Transform ->\n// createWriteStream, in a temp directory that is removed at the end.\n// Why this order: the callback form of pipeline calls back once, after the\n// destination stream has finished and closed; the check of the output file\n// is done inside that callback, so it sees the complete result. Reads and\n// writes use the thread pool, but we print only the start and the end, which\n// are ordered by the pipeline itself.\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\nconst { Transform, pipeline } = require('stream');\n\nconst dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-map-corpus-'));\nconst input = path.join(dir, 'in.txt');\nconst output = path.join(dir, 'out.txt');\nfs.writeFileSync(input, 'hello streams');\n\nconst upper = new Transform({\n transform(chunk, enc, cb) {\n cb(null, chunk.toString().toUpperCase());\n },\n});\n\npipeline(fs.createReadStream(input), upper, fs.createWriteStream(output), (err) => {\n console.log('pipeline done: err=' + err);\n console.log('output: ' + fs.readFileSync(output, 'utf8'));\n fs.rmSync(dir, { recursive: true, force: true });\n console.log('cleaned up: ' + !fs.existsSync(dir));\n});\nconsole.log('sync: pipeline started');\n","racy":false},{"id":"worker-roundtrip","title":"worker_threads message round trip","summary":"A worker has its own thread and event loop; messages arrive on the main event loop, exit comes after. The worker does not print; console output from workers is forwarded asynchronously.","module":"commonjs","text":"// Shows: worker_threads, one message round trip. The same file is both the\n// main program and the worker (told apart by isMainThread).\n// Why this order: the worker starts on its own thread with its own event\n// loop, so the main script continues at once (\"worker created\"). The reply is\n// delivered to the main thread's event loop as a message, and the 'exit'\n// event comes after the worker has finished. The worker prints nothing\n// itself: console output from a worker is forwarded to the main thread\n// asynchronously, which would make the order racy. The worker closes its\n// port after replying so that it can exit.\nconst { Worker, isMainThread, parentPort, workerData } = require('worker_threads');\n\nif (isMainThread) {\n const worker = new Worker(__filename, { workerData: { base: 20 } });\n console.log('main: worker created');\n worker.on('message', (msg) => console.log('main: reply ' + JSON.stringify(msg)));\n worker.on('exit', (code) => console.log('main: worker exit code ' + code));\n worker.postMessage({ n: 1 });\n} else {\n parentPort.on('message', (msg) => {\n parentPort.postMessage({ sum: workerData.base + msg.n, isMainThread });\n parentPort.close();\n });\n}\n","racy":false},{"id":"microtask-starvation","title":"Bounded microtask starvation of a timer","summary":"Microtask queue drains completely before the loop continues.","module":"commonjs","text":"// Shows: a long chain of microtasks delays a timer (bounded version).\n// Why: the microtask queue is drained completely before control goes back to\n// the event loop, including microtasks queued while draining. Here each\n// microtask queues the next one, 100000 times. The 1 ms timer may well be\n// due before that finishes, yet it cannot run until the chain ends, so it\n// always sees the full count. The chain is finite, so the program finishes.\nconst TOTAL = 100000;\nlet count = 0;\n\nfunction step() {\n count += 1;\n if (count < TOTAL) queueMicrotask(step);\n}\n\nsetTimeout(() => console.log('timeout 1ms ran after ' + count + ' microtasks'), 1);\nqueueMicrotask(step);\nconsole.log('sync end, microtasks so far: ' + count);\n","racy":false},{"id":"tick-starvation","title":"Bounded nextTick starvation of promises","summary":"Tick queue drains completely before microtasks run.","module":"commonjs","text":"// Shows: nextTick callbacks can delay promise jobs (bounded version).\n// Why: Node runs the whole nextTick queue, including ticks queued while it\n// runs, before it drains the microtask queue. A promise reaction queued first\n// therefore waits for a chain of 1000 ticks, and so does the immediate. The\n// chain is finite, so the program finishes.\nconst TOTAL = 1000;\nlet count = 0;\n\nfunction tick() {\n count += 1;\n if (count < TOTAL) process.nextTick(tick);\n}\n\nPromise.resolve().then(() => console.log('promise reaction ran after ' + count + ' ticks'));\nsetImmediate(() => console.log('immediate ran after ' + count + ' ticks'));\nprocess.nextTick(tick);\nconsole.log('sync end, ticks so far: ' + count);\n","racy":false}]}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|