nodejs-map 0.0.0-stage → 0.1.1

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.
Files changed (238) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +95 -2
  3. package/dist/app/assets/LearnView-Cqz9Ux8w.js +3 -0
  4. package/dist/app/assets/LearnView-Cqz9Ux8w.js.map +1 -0
  5. package/dist/app/assets/LearnView-Nrw6YQU8.css +1 -0
  6. package/dist/app/assets/app.worker-DZKurLgd.js +8 -0
  7. package/dist/app/assets/app.worker-DZKurLgd.js.map +1 -0
  8. package/dist/app/assets/atlas.worker-DGHewGIv.js +2 -0
  9. package/dist/app/assets/atlas.worker-DGHewGIv.js.map +1 -0
  10. package/dist/app/assets/cm-BTWjV_Gb.js +13 -0
  11. package/dist/app/assets/cm-BTWjV_Gb.js.map +1 -0
  12. package/dist/app/assets/dist-B37Ex44M.js +2 -0
  13. package/dist/app/assets/dist-B37Ex44M.js.map +1 -0
  14. package/dist/app/assets/dist-Dv4HNg5q.js +2 -0
  15. package/dist/app/assets/dist-Dv4HNg5q.js.map +1 -0
  16. package/dist/app/assets/index-BRoted4h.css +1 -0
  17. package/dist/app/assets/index-eLItdROg.js +18 -0
  18. package/dist/app/assets/index-eLItdROg.js.map +1 -0
  19. package/dist/app/assets/map-CISW7_cc.css +1 -0
  20. package/dist/app/assets/map-mCCk9DTc.js +132 -0
  21. package/dist/app/assets/map-mCCk9DTc.js.map +1 -0
  22. package/dist/app/assets/sdf-label-font-1nAa0TP8.png +0 -0
  23. package/dist/app/config.json +5 -0
  24. package/dist/app/favicon.svg +1 -0
  25. package/dist/app/index.html +21 -0
  26. package/dist/atlas/v26.13.1/build-report.json +178 -0
  27. package/dist/atlas/v26.13.1/chunks/lib.bootstrap.0.json +1 -0
  28. package/dist/atlas/v26.13.1/chunks/lib.core.0.json +1 -0
  29. package/dist/atlas/v26.13.1/chunks/lib.crypto.0.json +1 -0
  30. package/dist/atlas/v26.13.1/chunks/lib.devtools.0.json +1 -0
  31. package/dist/atlas/v26.13.1/chunks/lib.events.0.json +1 -0
  32. package/dist/atlas/v26.13.1/chunks/lib.fs.0.json +1 -0
  33. package/dist/atlas/v26.13.1/chunks/lib.modules.0.json +1 -0
  34. package/dist/atlas/v26.13.1/chunks/lib.net.0.json +1 -0
  35. package/dist/atlas/v26.13.1/chunks/lib.net.1.json +1 -0
  36. package/dist/atlas/v26.13.1/chunks/lib.platform.0.json +1 -0
  37. package/dist/atlas/v26.13.1/chunks/lib.process.0.json +1 -0
  38. package/dist/atlas/v26.13.1/chunks/lib.rest.0.json +1 -0
  39. package/dist/atlas/v26.13.1/chunks/lib.streams.0.json +1 -0
  40. package/dist/atlas/v26.13.1/chunks/lib.timers.0.json +1 -0
  41. package/dist/atlas/v26.13.1/chunks/lib.workers.0.json +1 -0
  42. package/dist/atlas/v26.13.1/chunks/lib.zlib.0.json +1 -0
  43. package/dist/atlas/v26.13.1/chunks/src.callbacks.0.json +1 -0
  44. package/dist/atlas/v26.13.1/chunks/src.crypto.0.json +1 -0
  45. package/dist/atlas/v26.13.1/chunks/src.diag.0.json +1 -0
  46. package/dist/atlas/v26.13.1/chunks/src.fs.0.json +1 -0
  47. package/dist/atlas/v26.13.1/chunks/src.inspector.0.json +1 -0
  48. package/dist/atlas/v26.13.1/chunks/src.loop.0.json +1 -0
  49. package/dist/atlas/v26.13.1/chunks/src.modules.0.json +1 -0
  50. package/dist/atlas/v26.13.1/chunks/src.napi.0.json +1 -0
  51. package/dist/atlas/v26.13.1/chunks/src.net.0.json +1 -0
  52. package/dist/atlas/v26.13.1/chunks/src.net.1.json +1 -0
  53. package/dist/atlas/v26.13.1/chunks/src.process.0.json +1 -0
  54. package/dist/atlas/v26.13.1/chunks/src.rest.0.json +1 -0
  55. package/dist/atlas/v26.13.1/chunks/src.support.0.json +1 -0
  56. package/dist/atlas/v26.13.1/chunks/src.zlib.0.json +1 -0
  57. package/dist/atlas/v26.13.1/chunks/uv.api.0.json +1 -0
  58. package/dist/atlas/v26.13.1/chunks/uv.backends.0.json +1 -0
  59. package/dist/atlas/v26.13.1/chunks/uv.fs.0.json +1 -0
  60. package/dist/atlas/v26.13.1/chunks/uv.loop.0.json +1 -0
  61. package/dist/atlas/v26.13.1/chunks/uv.net.0.json +1 -0
  62. package/dist/atlas/v26.13.1/chunks/uv.rest.0.json +1 -0
  63. package/dist/atlas/v26.13.1/chunks/uv.threadpool.0.json +1 -0
  64. package/dist/atlas/v26.13.1/chunks/v8.api.0.json +1 -0
  65. package/dist/atlas/v26.13.1/chunks/v8.asmjs.0.json +1 -0
  66. package/dist/atlas/v26.13.1/chunks/v8.ast.0.json +1 -0
  67. package/dist/atlas/v26.13.1/chunks/v8.base.0.json +1 -0
  68. package/dist/atlas/v26.13.1/chunks/v8.baseline.0.json +1 -0
  69. package/dist/atlas/v26.13.1/chunks/v8.bigint.0.json +1 -0
  70. package/dist/atlas/v26.13.1/chunks/v8.builtins.0.json +1 -0
  71. package/dist/atlas/v26.13.1/chunks/v8.codegen.0.json +1 -0
  72. package/dist/atlas/v26.13.1/chunks/v8.codegen.riscv.0.json +1 -0
  73. package/dist/atlas/v26.13.1/chunks/v8.common.0.json +1 -0
  74. package/dist/atlas/v26.13.1/chunks/v8.compiler-dispatcher.0.json +1 -0
  75. package/dist/atlas/v26.13.1/chunks/v8.compiler.0.json +1 -0
  76. package/dist/atlas/v26.13.1/chunks/v8.compiler.backend.0.json +1 -0
  77. package/dist/atlas/v26.13.1/chunks/v8.compiler.turboshaft.0.json +1 -0
  78. package/dist/atlas/v26.13.1/chunks/v8.d8.0.json +1 -0
  79. package/dist/atlas/v26.13.1/chunks/v8.date.0.json +1 -0
  80. package/dist/atlas/v26.13.1/chunks/v8.debug.0.json +1 -0
  81. package/dist/atlas/v26.13.1/chunks/v8.deoptimizer.0.json +1 -0
  82. package/dist/atlas/v26.13.1/chunks/v8.diagnostics.0.json +1 -0
  83. package/dist/atlas/v26.13.1/chunks/v8.dumpling.0.json +1 -0
  84. package/dist/atlas/v26.13.1/chunks/v8.execution.0.json +1 -0
  85. package/dist/atlas/v26.13.1/chunks/v8.extensions.0.json +1 -0
  86. package/dist/atlas/v26.13.1/chunks/v8.flags.0.json +1 -0
  87. package/dist/atlas/v26.13.1/chunks/v8.fuzzilli.0.json +1 -0
  88. package/dist/atlas/v26.13.1/chunks/v8.handles.0.json +1 -0
  89. package/dist/atlas/v26.13.1/chunks/v8.heap.0.json +1 -0
  90. package/dist/atlas/v26.13.1/chunks/v8.heap.cppgc.0.json +1 -0
  91. package/dist/atlas/v26.13.1/chunks/v8.ic.0.json +1 -0
  92. package/dist/atlas/v26.13.1/chunks/v8.init.0.json +1 -0
  93. package/dist/atlas/v26.13.1/chunks/v8.inspector.0.json +1 -0
  94. package/dist/atlas/v26.13.1/chunks/v8.interpreter.0.json +1 -0
  95. package/dist/atlas/v26.13.1/chunks/v8.json.0.json +1 -0
  96. package/dist/atlas/v26.13.1/chunks/v8.libplatform.0.json +1 -0
  97. package/dist/atlas/v26.13.1/chunks/v8.libsampler.0.json +1 -0
  98. package/dist/atlas/v26.13.1/chunks/v8.logging.0.json +1 -0
  99. package/dist/atlas/v26.13.1/chunks/v8.maglev.0.json +1 -0
  100. package/dist/atlas/v26.13.1/chunks/v8.numbers.0.json +1 -0
  101. package/dist/atlas/v26.13.1/chunks/v8.objects.0.json +1 -0
  102. package/dist/atlas/v26.13.1/chunks/v8.parsing.0.json +1 -0
  103. package/dist/atlas/v26.13.1/chunks/v8.profiler.0.json +1 -0
  104. package/dist/atlas/v26.13.1/chunks/v8.regexp.0.json +1 -0
  105. package/dist/atlas/v26.13.1/chunks/v8.root.0.json +1 -0
  106. package/dist/atlas/v26.13.1/chunks/v8.roots.0.json +1 -0
  107. package/dist/atlas/v26.13.1/chunks/v8.runtime.0.json +1 -0
  108. package/dist/atlas/v26.13.1/chunks/v8.sandbox.0.json +1 -0
  109. package/dist/atlas/v26.13.1/chunks/v8.snapshot.0.json +1 -0
  110. package/dist/atlas/v26.13.1/chunks/v8.strings.0.json +1 -0
  111. package/dist/atlas/v26.13.1/chunks/v8.tasks.0.json +1 -0
  112. package/dist/atlas/v26.13.1/chunks/v8.torque.0.json +1 -0
  113. package/dist/atlas/v26.13.1/chunks/v8.tracing.0.json +1 -0
  114. package/dist/atlas/v26.13.1/chunks/v8.trap-handler.0.json +1 -0
  115. package/dist/atlas/v26.13.1/chunks/v8.utils.0.json +1 -0
  116. package/dist/atlas/v26.13.1/chunks/v8.wasm.0.json +1 -0
  117. package/dist/atlas/v26.13.1/chunks/v8.zone.0.json +1 -0
  118. package/dist/atlas/v26.13.1/edges.json +1 -0
  119. package/dist/atlas/v26.13.1/files.json +1 -0
  120. package/dist/atlas/v26.13.1/index.json +1 -0
  121. package/dist/atlas/v26.13.1/search.json +1 -0
  122. package/dist/cli.js +6268 -0
  123. package/dist/examples.json +1 -0
  124. package/dist/learn/async-await.json +1 -0
  125. package/dist/learn/backpressure.json +1 -0
  126. package/dist/learn/big-picture.json +1 -0
  127. package/dist/learn/blocking-the-loop.json +1 -0
  128. package/dist/learn/breakpoints.json +1 -0
  129. package/dist/learn/call-stack.json +1 -0
  130. package/dist/learn/first-run.json +1 -0
  131. package/dist/learn/follow-readfile.json +1 -0
  132. package/dist/learn/four-threads-six-jobs.json +1 -0
  133. package/dist/learn/glossary.json +1 -0
  134. package/dist/learn/hiding-areas.json +1 -0
  135. package/dist/learn/http-one-request.json +1 -0
  136. package/dist/learn/http-two-requests.json +1 -0
  137. package/dist/learn/img/big-picture.webp +0 -0
  138. package/dist/learn/img/first-run-queues.webp +0 -0
  139. package/dist/learn/img/hide-restore-strip.webp +0 -0
  140. package/dist/learn/img/hide-view-menu.webp +0 -0
  141. package/dist/learn/img/map-call-path.webp +0 -0
  142. package/dist/learn/img/marks-in-a-run.webp +0 -0
  143. package/dist/learn/img/paused-at-breakpoint.webp +0 -0
  144. package/dist/learn/img/paused-in-node-fs.webp +0 -0
  145. package/dist/learn/img/playback-bar.webp +0 -0
  146. package/dist/learn/img/save-and-share.webp +0 -0
  147. package/dist/learn/img/tour-areas.webp +0 -0
  148. package/dist/learn/index.json +390 -0
  149. package/dist/learn/keep-alive.json +1 -0
  150. package/dist/learn/loop-phases.json +1 -0
  151. package/dist/learn/many-clients.json +1 -0
  152. package/dist/learn/microtasks-belong-to-v8.json +1 -0
  153. package/dist/learn/next-tick.json +1 -0
  154. package/dist/learn/observed-and-inferred.json +1 -0
  155. package/dist/learn/one-libuv-timer.json +1 -0
  156. package/dist/learn/order-and-esm.json +1 -0
  157. package/dist/learn/pipeline-errors.json +1 -0
  158. package/dist/learn/playback.json +1 -0
  159. package/dist/learn/pool-size.json +1 -0
  160. package/dist/learn/prerequisites.json +1 -0
  161. package/dist/learn/probe-build.json +1 -0
  162. package/dist/learn/promises-and-microtasks.json +1 -0
  163. package/dist/learn/reading-a-file.json +1 -0
  164. package/dist/learn/rec/async-await-chain.nmrec.gz +0 -0
  165. package/dist/learn/rec/backpressure.nmrec.gz +0 -0
  166. package/dist/learn/rec/beforeexit-and-exit.nmrec.gz +0 -0
  167. package/dist/learn/rec/block-loop.nmrec.gz +0 -0
  168. package/dist/learn/rec/dns-lookup-thread-pool.nmrec.gz +0 -0
  169. package/dist/learn/rec/esm-twist.nmrec.gz +0 -0
  170. package/dist/learn/rec/eventemitter-is-synchronous.nmrec.gz +0 -0
  171. package/dist/learn/rec/first-run.nmrec.gz +0 -0
  172. package/dist/learn/rec/fs-promises-await.nmrec.gz +0 -0
  173. package/dist/learn/rec/fs-sync-vs-async.nmrec.gz +0 -0
  174. package/dist/learn/rec/http-blocking-fixed.nmrec.gz +0 -0
  175. package/dist/learn/rec/http-blocking.nmrec.gz +0 -0
  176. package/dist/learn/rec/http-keep-alive.nmrec.gz +0 -0
  177. package/dist/learn/rec/http-roundtrip.nmrec.gz +0 -0
  178. package/dist/learn/rec/http-two-requests.nmrec.gz +0 -0
  179. package/dist/learn/rec/interval-and-clear.nmrec.gz +0 -0
  180. package/dist/learn/rec/nested-ticks-and-microtasks.nmrec.gz +0 -0
  181. package/dist/learn/rec/next-tick.nmrec.gz +0 -0
  182. package/dist/learn/rec/pbkdf2-six-jobs-four-threads.nmrec.gz +0 -0
  183. package/dist/learn/rec/phase-check.nmrec.gz +0 -0
  184. package/dist/learn/rec/phase-close.nmrec.gz +0 -0
  185. package/dist/learn/rec/phase-io.nmrec.gz +0 -0
  186. package/dist/learn/rec/pipeline-error.nmrec.gz +0 -0
  187. package/dist/learn/rec/pool-users.nmrec.gz +0 -0
  188. package/dist/learn/rec/pool-with-two-threads.nmrec.gz +0 -0
  189. package/dist/learn/rec/promise-microtasks.nmrec.gz +0 -0
  190. package/dist/learn/rec/readfile-thread-pool.nmrec.gz +0 -0
  191. package/dist/learn/rec/run-to-completion.nmrec.gz +0 -0
  192. package/dist/learn/rec/split-work.nmrec.gz +0 -0
  193. package/dist/learn/rec/stream-pipeline-file.nmrec.gz +0 -0
  194. package/dist/learn/rec/streams-memory.nmrec.gz +0 -0
  195. package/dist/learn/rec/tcp-many-clients.nmrec.gz +0 -0
  196. package/dist/learn/rec/tcp-round-trip.nmrec.gz +0 -0
  197. package/dist/learn/rec/tick-before-promise.nmrec.gz +0 -0
  198. package/dist/learn/rec/timeout-vs-immediate-io.nmrec.gz +0 -0
  199. package/dist/learn/rec/timeout-vs-immediate-main.nmrec.gz +0 -0
  200. package/dist/learn/rec/timer-lateness.nmrec.gz +0 -0
  201. package/dist/learn/rec/timer-vs-file-read.nmrec.gz +0 -0
  202. package/dist/learn/rec/timers-phase.nmrec.gz +0 -0
  203. package/dist/learn/rec/unref-timer.nmrec.gz +0 -0
  204. package/dist/learn/save-and-share.json +1 -0
  205. package/dist/learn/slow-handler.json +1 -0
  206. package/dist/learn/splitting-work.json +1 -0
  207. package/dist/learn/staying-alive.json +1 -0
  208. package/dist/learn/stepping-into-node.json +1 -0
  209. package/dist/learn/streams-basics.json +1 -0
  210. package/dist/learn/tcp-step-by-step.json +1 -0
  211. package/dist/learn/the-map.json +1 -0
  212. package/dist/learn/three-marks.json +1 -0
  213. package/dist/learn/timeout-vs-immediate.json +1 -0
  214. package/dist/learn/timers-are-not-now.json +1 -0
  215. package/dist/learn/tour.json +1 -0
  216. package/dist/learn/what-it-is.json +1 -0
  217. package/dist/learn/what-uses-the-pool.json +1 -0
  218. package/dist/lessons/async-await-chain.nmrec.gz +0 -0
  219. package/dist/lessons/beforeexit-and-exit.nmrec.gz +0 -0
  220. package/dist/lessons/dns-lookup-thread-pool.nmrec.gz +0 -0
  221. package/dist/lessons/esm-twist.nmrec.gz +0 -0
  222. package/dist/lessons/eventemitter-is-synchronous.nmrec.gz +0 -0
  223. package/dist/lessons/fs-promises-await.nmrec.gz +0 -0
  224. package/dist/lessons/fs-sync-vs-async.nmrec.gz +0 -0
  225. package/dist/lessons/index.json +621 -0
  226. package/dist/lessons/interval-and-clear.nmrec.gz +0 -0
  227. package/dist/lessons/nested-ticks-and-microtasks.nmrec.gz +0 -0
  228. package/dist/lessons/pbkdf2-six-jobs-four-threads.nmrec.gz +0 -0
  229. package/dist/lessons/pool-with-two-threads.nmrec.gz +0 -0
  230. package/dist/lessons/readfile-thread-pool.nmrec.gz +0 -0
  231. package/dist/lessons/tcp-round-trip.nmrec.gz +0 -0
  232. package/dist/lessons/tick-before-promise.nmrec.gz +0 -0
  233. package/dist/lessons/timeout-vs-immediate-io.nmrec.gz +0 -0
  234. package/dist/lessons/timeout-vs-immediate-main.nmrec.gz +0 -0
  235. package/dist/lessons/timer-vs-file-read.nmrec.gz +0 -0
  236. package/dist/lessons/timers-phase.nmrec.gz +0 -0
  237. package/dist/preload.cjs +507 -0
  238. 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}]}
@@ -0,0 +1 @@
1
+ {"id":"async-await","chapter":"event-loop","title":"async/await is promises","summary":"An async function runs right away up to its first await. Everything after an await runs later, as a promise callback, which is a microtask.","blocks":[{"t":"p","text":["By the end of this lesson you can point at any line of an async function and say whether it runs right away or later as a microtask, and what it waits for."]},{"t":"h","level":2,"id":"a-chain-of-async-functions","text":"A chain of async functions"},{"t":"example","example":"async-await-chain"},{"t":"p","text":["Three async functions call each other, ",{"t":"code","text":"a"}," calls ",{"t":"code","text":"b"}," and ",{"t":"code","text":"b"}," calls ",{"t":"code","text":"c"},". Then ",{"t":"code","text":"a"}," waits for a 1 ms timer."]},{"t":"p","text":["Step through it with ",{"t":"ui","text":"Queues"}," and ",{"t":"ui","text":"Stack"}," open. What you see:"]},{"t":"list","ordered":false,"items":[["Calling ",{"t":"code","text":"a()"}," runs ",{"t":"code","text":"a"},", ",{"t":"code","text":"b"}," and ",{"t":"code","text":"c"}," straight away, as ordinary function calls, until ",{"t":"code","text":"c"}," reaches ",{"t":"code","text":"await null"},". All of that is still the script."],[{"t":"code","text":"await x"}," means: stop this function here, and continue it in a microtask once ",{"t":"code","text":"x"}," has settled. The rest of the function becomes a promise callback. ",{"t":"ui","text":"Stack"}," shows it as a \"promise reaction\", the name V8 gives a promise callback."],[{"t":"code","text":"b"}," can only continue when ",{"t":"code","text":"c"}," has finished, and ",{"t":"code","text":"a"}," when ",{"t":"code","text":"b"}," has. That is three microtasks, one after the other, in the same round of the microtask queue."],[{"t":"code","text":"await sleep(1)"}," waits for a timer. The timer's callback resolves the promise, and the rest of ",{"t":"code","text":"a"}," runs as a microtask right after the timer's callback, still in the timers phase."]]},{"t":"h","level":2,"id":"await-with-real-i-o","text":"await with real I/O"},{"t":"example","example":"fs-promises-await"},{"t":"p","text":["With ",{"t":"code","text":"fs.promises"},", each ",{"t":"code","text":"await"}," waits for a request to the file system. The request goes to the thread pool. When it comes back, the code after the ",{"t":"code","text":"await"}," runs as a microtask, right after the request's own callback, in the same step of the loop."]},{"t":"note","kind":"tip","text":["An ",{"t":"code","text":"await"}," hands the main thread back. It ends the current piece of JavaScript, and the rest of the function runs later, as a new microtask."]},{"t":"check","question":[{"t":"code","text":"async function f() { console.log(1); await null; console.log(2); } f(); console.log(3);"}," What is printed?"],"answer":["1, 3, 2. The function runs right away up to the ",{"t":"code","text":"await"}," and prints 1. The script prints 3. Then the rest of ",{"t":"code","text":"f"}," runs as a microtask and prints 2."]}],"examples":{"async-await-chain":{"id":"async-await-chain","title":"An async/await chain: where each continuation runs","name":"async-await-chain.js","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,"output":["a start","b start","c start","sync end","nextTick","c resumed (microtask)","b resumed with c-value","a resumed with b-value","a resumed after timer","a() promise resolved"],"recording":"rec/async-await-chain.nmrec.gz","steps":[{"index":27,"title":"a, b and c start right away","text":"Calling a() ran a, b and c, one inside the other, until c reached `await null`. All of this is still the script: no callback is running."},{"index":39,"title":"Only c can go on yet","text":"The script is done. The microtask queue lists one \"promise reaction\": the rest of c, because `await null` can go on at once. b and a wait for promises that have not settled yet, so they are not listed (inferred)."},{"index":45,"title":"Ticks first","text":"As in every CommonJS script, the nextTick queue is emptied before any microtask runs."},{"index":54,"title":"c goes on in a microtask","text":"Now c continues after `await null`. On the Stack tab, the code after an await is a \"promise reaction\" callback that came from the microtask queue."},{"index":72,"title":"Then b, then a","text":"b and then a go on, each in its own microtask, all in the same round of the microtask queue: no phase of the loop runs in between. Each joined the queue only when the promise it awaited settled: b's when c returned, a's when b returned."},{"index":97,"title":"A timer settles the last await","text":"`await sleep(1)` waits for a timer, the \"setTimeout 1 ms\" chip. The timer's callback resolves the promise, and the rest of a() runs as a microtask right after it, still in the timers phase."},{"index":107,"title":"a() settles","text":"Finally the promise returned by a() settles, and the .then callback from the script runs, again as a microtask."}]},"fs-promises-await":{"id":"fs-promises-await","title":"fs.promises with await","name":"fs-promises-await.js","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,"output":["main start","sync: after main() call","nextTick","written","read: abc","main resolved: finished"],"recording":"rec/fs-promises-await.nmrec.gz","steps":[{"index":17,"title":"Right away up to the first await","text":"main() runs as part of the script until its first await, on fsp.mkdtemp."},{"index":34,"title":"main() waits","text":"The await on mkdtemp paused main(), so the script carries on. The \"fs.mkdtemp\" request (type FSREQPROMISE) is with the thread pool."},{"index":40,"title":"Ticks before any file result","text":"The tick runs as soon as the script is done. No file result has come back yet."},{"index":102,"title":"Going on after the write","text":"The write finished on the thread pool, and the code after `await fsp.writeFile` runs as a microtask (see the Stack tab), in the same step of the loop as the request's callback."},{"index":144,"title":"Read back","text":"The same happens for the read: one trip to the thread pool, then a microtask continues main()."},{"index":280,"title":"Seven requests to remove a folder","text":"fsp.rm with recursive: true made seven requests, one after another (lstat, lstat, rmdir, scandir, lstat, unlink, rmdir), each a trip to the thread pool and back. Only then does main() finish."}]}},"prev":{"id":"promises-and-microtasks","title":"Promises and microtasks"},"next":{"id":"order-and-esm","title":"The order: ticks, microtasks, then the loop, and the ES module twist"}}
@@ -0,0 +1 @@
1
+ {"id":"backpressure","chapter":"streams","title":"Backpressure made visible","summary":"write() returns false when a writable's buffer is full. Wait for 'drain' before writing more, and memory stays small however slow the destination is.","blocks":[{"t":"p","text":["By the end of this lesson you can explain what ",{"t":"code","text":"write()"}," returning false means and what to do about it."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"p","text":["A writable stream has a ",{"t":"strong","text":"highWaterMark"},": the amount of waiting data at which ",{"t":"code","text":"write()"}," starts returning false. In this program it is only 3 bytes, and the stream finishes each write one loop turn later. The program writes chunks of 2 bytes and listens for ",{"t":"code","text":"'drain'"},"."]},{"t":"example","example":"backpressure"},{"t":"h","level":2,"id":"what-you-saw","text":"What you saw"},{"t":"list","ordered":false,"items":[[{"t":"code","text":"write()"}," puts the chunk in the stream's buffer and returns whether there is still room. After two chunks, 4 bytes are waiting to be written, more than 3, so it returns false."],["false still takes the chunk: it is buffered. The return value means \"stop for now\"."],["When the destination has worked through the buffer, the stream emits ",{"t":"code","text":"'drain'"},", and the program writes again. Here each write finishes in a ",{"t":"code","text":"setImmediate"}," callback, so ",{"t":"code","text":"'drain'"}," comes from the check phase."]]},{"t":"p","text":["This is ",{"t":"strong","text":"backpressure"},": a slow destination pushes back on a fast source, and the source waits. Ignoring false would still work in this tiny program, but with a slow destination and a fast source the buffer would grow without limit. ",{"t":"code","text":"pipeline"}," and ",{"t":"code","text":"pipe"}," do this waiting for you."]},{"t":"check","question":["A program reads a 1 GB file and writes it to a slow network socket with ",{"t":"code","text":"socket.write()"}," in a loop, ignoring the return value. What grows?"],"answer":["The socket's write buffer: memory use grows towards the size of the file, because the program keeps writing while the destination cannot keep up."]}],"examples":{"backpressure":{"id":"backpressure","title":"write() returns false","name":"backpressure.js","module":"commonjs","text":"// Backpressure: write() returns false when the writable's buffer is full; 'drain' says \"go on\".\nconst { Writable } = require('stream');\n\nconst slow = new Writable({\n highWaterMark: 3, // bytes\n write(chunk, enc, done) {\n setImmediate(done); // a slow destination: each write finishes a loop turn later\n },\n});\n\nlet i = 0;\nfunction writeMore() {\n while (i < 6) {\n const ok = slow.write('ab');\n console.log('write ' + ++i + ' -> ' + ok);\n if (!ok) return slow.once('drain', () => { console.log('drain'); writeMore(); });\n }\n slow.end(() => console.log('all written'));\n}\nwriteMore();\n","racy":false,"output":["write 1 -> true","write 2 -> false","drain","write 3 -> true","write 4 -> false","drain","write 5 -> true","write 6 -> false","drain","all written"],"recording":"rec/backpressure.nmrec.gz","steps":[{"index":23,"title":"The buffer is full","text":"After two writes, 4 bytes are waiting to be written, more than the highWaterMark of 3, so write() returns false: stop for now."},{"index":45,"title":"drain","text":"The destination finishes each write one loop turn later, in a setImmediate callback. When its buffer is empty, 'drain' fires inside that callback, in the check phase."},{"index":122,"title":"All written","text":"Writing went on in rounds of two, each round waiting for 'drain'."}]}},"prev":{"id":"streams-basics","title":"Readable, writable, transform in ten lines"},"next":{"id":"pipeline-errors","title":"pipeline and errors"}}
@@ -0,0 +1 @@
1
+ {"id":"big-picture","chapter":"before","title":"Node.js under the hood: the big picture","summary":"The parts of Node.js in plain words and one picture. V8, Node's JavaScript library, the C++ bindings, libuv with its event loop and thread pool, and the operating system.","blocks":[{"t":"p","text":["By the end of this lesson you can name the main parts of Node.js, say in a sentence what each one does, and say which part does what when a small program runs."]},{"t":"h","level":2,"id":"a-small-program","text":"A small program"},{"t":"code","lang":"js","text":"const fs = require('fs');\n\nfs.readFile('notes.txt', 'utf8', (err, text) => {\n console.log('file read');\n});\nsetTimeout(() => console.log('timer fired'), 10);\nconsole.log('script done');"},{"t":"p","text":["You know what it prints first: \"script done\". The other two lines come later."]},{"t":"p","text":["Where are the file and the timer while the script goes on? What decides when their callbacks run? This lesson follows the program through Node to answer that. Here are the parts of Node that take part. The sections below explain them one by one."]},{"t":"image","src":"img/big-picture.webp","alt":"The parts of Node.js, from your program down to the operating system","width":1840,"height":1280,"caption":"The parts of Node.js, and how they connect. Each part is explained below."},{"t":"h","level":2,"id":"threads","text":"Threads"},{"t":"p","text":["A ",{"t":"strong","text":"thread"}," is one line of work inside a running program: a list of instructions that the computer carries out one after the other. A program can have several threads, and the computer can run them at the same time, on different CPU cores."]},{"t":"p","text":["Node runs all of your JavaScript on one thread, called the ",{"t":"strong","text":"main thread"},". So your JavaScript runs one piece at a time, in a single line of work."]},{"t":"h","level":2,"id":"v8-runs-javascript","text":"V8 runs JavaScript"},{"t":"p","text":[{"t":"strong","text":"V8"}," is the JavaScript engine inside Node. It is the same engine that runs JavaScript in Chrome. V8 turns JavaScript into machine code and runs it, on the main thread."]},{"t":"p","text":["V8 knows the JavaScript language itself: values, functions, objects, promises. Files, network connections and timers come from Node, which builds them around V8."]},{"t":"h","level":2,"id":"node-s-own-javascript","text":"Node's own JavaScript"},{"t":"p","text":["The modules you ",{"t":"code","text":"require"},", such as ",{"t":"code","text":"fs"},", ",{"t":"code","text":"http"},", ",{"t":"code","text":"net"},", ",{"t":"code","text":"events"}," and ",{"t":"code","text":"timers"},", are mostly written in JavaScript. That code is ",{"t":"strong","text":"Node's JavaScript library"},". It lives in the ",{"t":"code","text":"lib/"}," folder of Node's source code, and V8 runs it on the main thread, just like your own code."]},{"t":"p","text":["When your program calls ",{"t":"code","text":"fs.readFile"},", the first code that runs is a JavaScript function in ",{"t":"code","text":"lib/fs.js"},". It checks your arguments. Then it needs something JavaScript cannot do by itself: ask the operating system to read a file."]},{"t":"h","level":2,"id":"the-c-bindings","text":"The C++ bindings"},{"t":"p","text":["Another part of Node is written in C++, in the ",{"t":"code","text":"src/"}," folder. A ",{"t":"strong","text":"binding"}," is a C++ function that Node's JavaScript library can call as if it were a JavaScript function."]},{"t":"p","text":["Bindings are the bridge between Node's JavaScript and the parts of Node that are not JavaScript. ",{"t":"code","text":"fs.readFile"}," calls a binding, and the binding hands the real work on to the next part."]},{"t":"h","level":2,"id":"libuv-everything-that-waits","text":"libuv: everything that waits"},{"t":"p","text":[{"t":"strong","text":"libuv"}," is a library written in C. Node uses it for everything that involves waiting: for a file to be read, for data to arrive on a network connection, for a timer to be due. libuv works the same way on Windows, Linux and macOS, so Node's other parts do not have to care which system they run on."]},{"t":"p","text":["libuv keeps track of two kinds of things:"]},{"t":"list","ordered":false,"items":[["A ",{"t":"strong","text":"handle"}," is something long-lived that can call back many times: a timer, a server, a network connection."],["A ",{"t":"strong","text":"request"}," is a one-off piece of work that calls back once: reading a file, or finding the address of a host name."]]},{"t":"h","level":2,"id":"the-event-loop","text":"The event loop"},{"t":"p","text":["The ",{"t":"strong","text":"event loop"}," is a loop in libuv. It runs on the main thread. Each time round, it looks at what has finished or become due, and calls back into JavaScript for each of those things, one at a time."]},{"t":"p","text":["One time round is called a ",{"t":"strong","text":"turn of the loop"},". A turn is made of fixed stops, always in the same order, called ",{"t":"strong","text":"phases"},". For example, one phase runs the timers that are due, and another delivers the results of finished file and network work. A later chapter goes through every phase."]},{"t":"p","text":["When nothing is due and nothing has finished, the event loop waits. While it waits, the program uses no CPU. When nothing is left that could ever call back, the loop ends, and so does the program."]},{"t":"p","text":["The main thread takes turns between your JavaScript and the event loop. While a piece of JavaScript runs, the event loop cannot go round. JavaScript that runs for a long time makes everything else wait."]},{"t":"h","level":2,"id":"queues","text":"Queues"},{"t":"p","text":["A callback that is ready to run, but has to wait until the main thread is free, sits in a ",{"t":"strong","text":"queue"},": a waiting line, where the first to join is the first to leave."]},{"t":"p","text":["Node has several queues, one for each kind of callback: one for timers, one for promise callbacks, and a few more. You will meet them one by one."]},{"t":"p","text":["A ",{"t":"strong","text":"microtask"}," is a small task, such as a promise callback, that runs as soon as the JavaScript that is running now has finished. Microtasks wait in a queue of their own, the microtask queue."]},{"t":"p","text":["Some articles speak of \"the\" ",{"t":"strong","text":"callback queue"},". In Node it is several queues, and the order in which Node empties them is what the event loop chapter is about."]},{"t":"h","level":2,"id":"the-thread-pool","text":"The thread pool"},{"t":"p","text":["Some work has to be waited out. Reading a file is the usual example: the operating system does it in one go and keeps the thread busy until it is finished. If the main thread did that work itself, everything else would have to wait."]},{"t":"p","text":["So libuv keeps a ",{"t":"strong","text":"thread pool"},": a few extra threads, four unless you ask for more, that do this kind of work away from the main thread. When a piece of work is done, the event loop picks up the result on the main thread and calls your callback. All of your JavaScript stays on the main thread."]},{"t":"h","level":2,"id":"the-operating-system","text":"The operating system"},{"t":"p","text":["At the bottom is the operating system: Windows, Linux or macOS. It does the real work of reading files, sending and receiving network data, and keeping time. libuv asks it for that work, and asks it what has finished."]},{"t":"p","text":["Network connections stay off the thread pool: the operating system can watch many connections at once and tell libuv which ones have data."]},{"t":"h","level":2,"id":"the-program-again","text":"The program again"},{"t":"p","text":["Now follow the small program through these parts:"]},{"t":"list","ordered":true,"items":[["V8 runs your script on the main thread. ",{"t":"code","text":"fs.readFile"}," runs Node's JavaScript in ",{"t":"code","text":"lib/fs.js"},", which calls a binding, which gives libuv a request, which libuv hands to the thread pool. ",{"t":"code","text":"setTimeout"}," asks for a timer. The script prints \"script done\" and ends."],["A pool thread reads the file. The main thread is free meanwhile."],["The event loop goes round. When the file has been read, the loop calls your callback, which prints \"file read\". When 10 ms have passed, the loop calls the timer's callback, which prints \"timer fired\". Both callbacks run on the main thread, one after the other."],["Nothing is left that could call back. The loop ends, and the program exits."]]},{"t":"p","text":["Look at the picture again. Everything in yellow runs on the main thread: your program, Node's JavaScript library, the C++ bindings and the event loop. The thread pool is four separate threads. The map of nodejs-map is drawn in the same layers: your program at the top, then Node's JavaScript library, the C++ bindings, V8 and libuv, and the operating system at the bottom."]},{"t":"check","question":["The file of the small program has been read by a pool thread. On which thread does the callback that prints \"file read\" run, and which part of Node calls it?"],"answer":["On the main thread. The event loop picks up the finished work and calls the callback, after the script has ended."]}],"examples":{},"prev":{"id":"hiding-areas","title":"Showing just the areas you need"},"next":{"id":"first-run","title":"Your first run"}}
@@ -0,0 +1 @@
1
+ {"id":"blocking-the-loop","chapter":"thread-pool","title":"Blocking the loop with CPU work","summary":"CPU work in JavaScript runs on the main thread. While it runs, due timers and finished I/O wait, all of them.","blocks":[{"t":"p","text":["By the end of this lesson you can explain why one slow function makes every timer late and every response slow."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"block-loop"},{"t":"p","text":["The script sets a 5 ms timer and starts an ",{"t":"code","text":"fs.stat"},", then computes for 100 ms."]},{"t":"h","level":2,"id":"what-you-saw","text":"What you saw"},{"t":"list","ordered":false,"items":[["While the script computes, the timer becomes due, and the stat request may well be answered already. Neither callback can run: the main thread is busy."],["When the script ends, the event loop runs the overdue timer first (due timers run once before the first turn), then delivers the stat result."],[{"t":"ui","text":"Queues"}," shows how late the timer started: about 100 ms."]]},{"t":"p","text":["This is what people mean when they say a program ",{"t":"strong","text":"blocks the event loop"},": while one piece of JavaScript runs, nothing else in the process can, however urgent."]},{"t":"note","kind":"tip","text":["Ways to move heavy work out of the way: split it into slices (",{"t":"link","text":"next lesson","href":"learn:splitting-work"},"), use an API that does the work on the thread pool, or run it on a ",{"t":"strong","text":"worker thread"},": a thread of its own, from Node's ",{"t":"code","text":"worker_threads"}," module, that runs JavaScript with its own event loop."]},{"t":"note","kind":"honest","text":["nodejs-map shows the messages a worker thread sends to the main thread. A view inside the worker itself is still to come."]},{"t":"check","question":["A server answers most requests in 1 ms, but one kind of request runs a loop for 300 ms. Two of those arrive at once. How long does a cheap request that arrives just after them wait?"],"answer":["About 600 ms: both expensive handlers run one after the other on the main thread before the cheap request can even be read."]}],"examples":{"block-loop":{"id":"block-loop","title":"CPU work blocks the loop","name":"block-loop.js","module":"commonjs","text":"// CPU work on the main thread blocks everything: due timers and finished I/O wait for it.\nconst fs = require('fs');\nconst start = Date.now();\n\nsetTimeout(() => {\n console.log('timer 5 ms: started at least 100 ms late = ' + (Date.now() - start >= 100));\n}, 5);\nfs.stat(__filename, () => console.log('stat callback: only after the busy work'));\n\nwhile (Date.now() - start < 100) {\n // 100 ms of CPU work on the main thread\n}\nconsole.log('script: 100 ms of work done');\n","racy":false,"output":["script: 100 ms of work done","timer 5 ms: started at least 100 ms late = true","stat callback: only after the busy work"],"recording":"rec/block-loop.nmrec.gz","steps":[{"index":23,"title":"100 ms of CPU work","text":"The script has spent about 100 ms computing. The 5 ms timer has been due for most of that time, and the \"fs.stat\" request is still listed with the pool: nothing could run."},{"index":34,"title":"The late timer","text":"As soon as the script is done, the loop runs the overdue timer. Timers shows it started about 100 ms late."},{"index":48,"title":"Then the I/O callback","text":"Then the stat callback runs. Every callback waited for the same CPU work."}]}},"prev":{"id":"what-uses-the-pool","title":"What uses the thread pool"},"next":{"id":"splitting-work","title":"Splitting work with setImmediate"}}
@@ -0,0 +1 @@
1
+ {"id":"breakpoints","chapter":"start","title":"Stopping at a line, and stepping","summary":"Stop your program at a line, go through it one statement at a time like in Chrome DevTools, and see why stopping can change what a program prints.","blocks":[{"t":"p","text":["By the end of this lesson you can stop a program at a line, step through it, and explain why stopping it can change what it prints."]},{"t":"h","level":2,"id":"this-needs-the-local-app","text":"This needs the local app"},{"t":"p","text":["Stopping a program means stopping a real, running program, so this lesson works in the local app, where your own programs run."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"p","text":["The program below reads a small file and sets a 5 ms timer. Whichever is ready first prints first. Two things that can finish in either order, depending on timing, are called a ",{"t":"strong","text":"race"},"."]},{"t":"example","example":"timer-vs-file-read"},{"t":"p","text":["Run it a few times: on most computers the file wins."]},{"t":"h","level":2,"id":"stop-at-a-line","text":"Stop at a line"},{"t":"p","text":["A ",{"t":"strong","text":"breakpoint"}," is a mark on a line of your program. When the program reaches that line, it stops before running it, and waits for you."]},{"t":"list","ordered":true,"items":[["Click ",{"t":"ui","text":"the line numbers"}," next to line 26, inside the timer's callback. A marker appears."],["Press ",{"t":"ui","text":"Run"},". The program runs until it reaches line 26, then stops."],["Press ",{"t":"ui","text":"Resume script execution"}," to let it run on."]]},{"t":"p","text":["While the program is stopped, ",{"t":"ui","text":"Stack"}," shows how it got to this line: the function that is running, the function that called it, and so on. It also shows the variables of each."]},{"t":"image","src":"img/paused-at-breakpoint.webp","alt":"A program stopped at a breakpoint","width":1280,"height":800,"caption":"While the program is stopped, the screen reminds you that real time keeps running."},{"t":"h","level":2,"id":"one-statement-at-a-time","text":"One statement at a time"},{"t":"p","text":["While the program is stopped, three buttons move it forward in small steps. They work like the same buttons in Chrome DevTools."]},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"Step over"}," (",{"t":"ui","text":"Step over next function call"},") runs the current statement, and stops at the next one. If the statement calls a function, the whole function runs."],[{"t":"strong","text":"Step into"}," (",{"t":"ui","text":"Step into next function call"},") goes into the function that the current statement calls, and stops at its first statement."],[{"t":"strong","text":"Step out"}," (",{"t":"ui","text":"Step out of current function"},") runs the rest of the current function, and stops right after the place that called it."]]},{"t":"h","level":2,"id":"what-stopping-changes","text":"What stopping changes"},{"t":"p","text":["A breakpoint stops only JavaScript. Everything else keeps going: the clock, and the pool thread that reads the file. Two small experiments show it."]},{"t":"p","text":["First, remove the breakpoint and set one on line 25, the ",{"t":"code","text":"setTimeout"}," call. Run, wait a few seconds, then resume. The file has been read on its pool thread while you waited, so when the script ends its result is already there."]},{"t":"p","text":["Second, set a breakpoint on line 22, inside the file's callback, and nothing else. Run, wait a few seconds in the callback, then resume. The 5 ms timer became due while you waited. It runs right after the file's callback, seconds late: open ",{"t":"ui","text":"Queues"}," to see how late."]},{"t":"p","text":["So a program that is stopped and resumed can behave differently from one that runs straight through. Keep that in mind whenever a race is involved."]},{"t":"note","kind":"honest","text":["On the official Node build the clock and the thread pool keep running while JavaScript is stopped, and the screen says so each time the program stops. A specially built Node can freeze the event loop's clock, and runs on Linux today: see ",{"t":"link","text":"the last lesson of the course","href":"learn:probe-build"},"."]},{"t":"check","question":["You stop inside a callback for ten seconds, then resume. A ",{"t":"code","text":"setTimeout(..., 1000)"}," was set just before you stopped. Does it fire one second after you resume?"],"answer":["No. Its due moment passed while the program was stopped. It fires as soon as the event loop reaches its timers again."]}],"examples":{"timer-vs-file-read":{"id":"timer-vs-file-read","title":"A 5 ms timer racing a file read","name":"timer-vs-readfile-race.js","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,"output":["file read","timer 5ms"],"recording":"rec/timer-vs-file-read.nmrec.gz","steps":[{"index":25,"title":"The read goes to the thread pool","text":"fs.readFile handed the file read to the thread pool: the \"fs.readFile\" request."},{"index":33,"title":"The 5 ms timer is set","text":"Then setTimeout set a 5 ms timer, the \"setTimeout 5 ms\" chip under Timers. From now on, the file read and the clock race each other."},{"index":35,"title":"The read finishes","text":"A pool thread has finished the read, and the result waits until the main thread picks it up. Reports from pool threads reach nodejs-map late, so where they sit against the main thread is approximate."},{"index":41,"title":"The file callback wins","text":"The file's callback runs first, on the main thread."},{"index":63,"title":"Then the timer","text":"The timer runs after it. Timers shows how late it started against its due moment. That lateness is nodejs-map's own arithmetic from the delay, not a report from Node."}]}},"prev":{"id":"the-map","title":"The map: where in Node is this?"},"next":{"id":"save-and-share","title":"Saving, opening and sharing a run"}}
@@ -0,0 +1 @@
1
+ {"id":"call-stack","chapter":"event-loop","title":"One thing at a time, to the end","summary":"Node runs one piece of JavaScript at a time, to its end. A timer that becomes due in the middle waits its turn.","blocks":[{"t":"p","text":["By the end of this lesson you can explain why a timer that is due still waits, and why an event listener runs before the line after ",{"t":"code","text":"emit()"},"."]},{"t":"h","level":2,"id":"a-due-timer-waits","text":"A due timer waits"},{"t":"example","example":"run-to-completion"},{"t":"p","text":["The program asks for a timer with a delay of 0 ms. Then it keeps the main thread busy for about 50 ms, in a loop that only checks the clock."]},{"t":"p","text":["Run it, and step through it with ",{"t":"ui","text":"Queues"}," open. The timer is due almost at once, yet its line comes last. For 50 ms it sits in the Timers queue, due and waiting."]},{"t":"h","level":2,"id":"why-run-to-completion","text":"Why: run to completion"},{"t":"p","text":["Node runs each piece of JavaScript to its end before it starts another. It runs your script until the script ends. It runs a callback until the callback returns. Only then does it look for the next thing to run."]},{"t":"p","text":["This is called ",{"t":"strong","text":"run to completion"},". It holds for every callback, not just for the script: while one runs, nothing else in the process runs JavaScript."]},{"t":"h","level":2,"id":"the-call-stack","text":"The call stack"},{"t":"p","text":["When a function calls another function, the first one waits until the second returns. The list of functions that are running and waiting in this way is the ",{"t":"strong","text":"call stack"},": the function running now is on top, the one that called it is below it, and so on, down to the script or callback that started it all."]},{"t":"p","text":["Run to completion means: Node only starts the next callback when the call stack is empty again."]},{"t":"p","text":["During a replay, ",{"t":"ui","text":"Stack"}," shows the callbacks on the main thread. When the program is stopped at a breakpoint, it shows the whole call stack, with the variables of each function."]},{"t":"h","level":2,"id":"emit-is-just-a-function-call","text":"emit() is just a function call"},{"t":"example","example":"eventemitter-is-synchronous"},{"t":"p","text":[{"t":"code","text":"emitter.emit('greet')"}," calls each listener directly, one after the other, before ",{"t":"code","text":"emit"}," returns. Nothing waits in a queue: watch ",{"t":"ui","text":"Queues"}," stay empty while the listeners print."]},{"t":"p","text":["So the line after ",{"t":"code","text":"emit()"}," runs after all the listeners. A listener only runs later if the program asks for that, as the second half of this program does. The next lessons explain how."]},{"t":"note","kind":"tip","text":["\"Asynchronous\" means \"later\", rather than \"at the same time\". Your callbacks run one after another. What happens at the same time is the work done elsewhere: by the operating system, and on the thread pool."]},{"t":"check","question":["A callback runs a loop that takes two seconds. Meanwhile data arrives on a network connection, and a timer becomes due. When do their callbacks run?"],"answer":["After the loop has finished and the callback has returned. Only then can the event loop run the overdue timer and deliver the data."]}],"examples":{"run-to-completion":{"id":"run-to-completion","title":"A due timer waits for running code","name":"run-to-completion.js","module":"commonjs","text":"// A due timer cannot interrupt running JavaScript: it waits until the script ends.\nconst start = Date.now();\n\nsetTimeout(() => {\n console.log('timer: ran after the busy loop');\n}, 0);\n\n// Keep the main thread busy for about 50 ms.\nwhile (Date.now() - start < 50) {\n // spin\n}\nconsole.log('script: busy loop done');\n","racy":false,"output":["script: busy loop done","timer: ran after the busy loop"],"recording":"rec/run-to-completion.nmrec.gz","steps":[{"index":17,"title":"A timer for 0 ms","text":"setTimeout with 0 ms puts a timer in Timers. Its chip says \"setTimeout 1 ms\": Node never waits less than 1 ms."},{"index":19,"title":"The loop keeps the thread busy","text":"About 50 ms later the busy loop ends. The timer has been due for almost all of that time, and it is still waiting: nothing interrupts JavaScript that is running."},{"index":30,"title":"Now the timer runs","text":"Only after the script has finished does the timer's callback run."}]},"eventemitter-is-synchronous":{"id":"eventemitter-is-synchronous","title":"EventEmitter is synchronous","name":"eventemitter-sync.js","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,"output":["before emit","listener 1","listener 2 (once)","listener 3","after emit (all listeners already ran)","nextTick: emit again","listener 1","listener 3","setImmediate: emit again","listener 1","listener 3"],"recording":"rec/eventemitter-is-synchronous.nmrec.gz","steps":[{"index":21,"title":"Listeners run inside emit()","text":"The first listener prints while the script is still running. The main thread shows the script, not a callback, and no queue was used."},{"index":30,"title":"emit() returns after all of them","text":"This line comes after all three listeners: emit() returned only when they had run."},{"index":46,"title":"Emitting from a later callback","text":"The second emit happens inside a callback that Node runs right after the script. The listeners run inside that callback (see the Stack tab). The once listener is gone, so only listeners 1 and 3 print."},{"index":66,"title":"Emitting from another later callback","text":"The third emit happens inside yet another callback that Node runs later. Again the listeners run inside it, one after the other."}]}},"prev":{"id":"save-and-share","title":"Saving, opening and sharing a run"},"next":{"id":"timers-are-not-now","title":"What a delay really means"}}
@@ -0,0 +1 @@
1
+ {"id":"first-run","chapter":"before","title":"Your first run","summary":"Run a tiny program, watch the replay, and read two tabs, Output and Queues, to see why its lines come out in the order they do.","blocks":[{"t":"p","text":["By the end of this lesson you can run a program in nodejs-map, watch its replay, and say for each line it printed what made that line run when it did."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"first-run"},{"t":"p","text":["The program prints three lines. Look at the order. The timer comes first in the code, but its line comes last."]},{"t":"h","level":2,"id":"run-it","text":"Run it"},{"t":"p","text":["In the local app, press ",{"t":"ui","text":"Run"},"."]},{"t":"p","text":["On the player website, press ",{"t":"ui","text":"Play the walk-through"}," under the program. It opens the recording that comes with this lesson, with a note for each step."]},{"t":"p","text":["Either way, you leave this page for the app. ",{"t":"ui","text":"Back to the lesson"}," at the top brings you back to the same place in the lesson."]},{"t":"h","level":2,"id":"the-replay","text":"The replay"},{"t":"p","text":["The program finishes in a few milliseconds. When a short program has ended, nodejs-map plays the run back from the start, slowly enough to follow. A long run waits at its start until you press ",{"t":"ui","text":"Play"},"."]},{"t":"p","text":["Three controls of the playback bar are all you need today:"]},{"t":"list","ordered":false,"items":[[{"t":"ui","text":"Play"}," plays the run, and pauses it."],[{"t":"ui","text":"Forward one step"}," moves one step forward. ",{"t":"ui","text":"Back one step"}," moves one step back."],[{"t":"ui","text":"the timeline"}," shows where you are in the run. Click anywhere on it to jump there."]]},{"t":"h","level":2,"id":"two-tabs","text":"Two tabs"},{"t":"p","text":["Of all the tabs in the panels, open only these two:"]},{"t":"list","ordered":false,"items":[[{"t":"ui","text":"Output"}," shows what the program printed, each line at the moment it was printed."],[{"t":"ui","text":"Queues"}," shows everything that is waiting to run."]]},{"t":"image","src":"img/first-run-queues.webp","alt":"The Queues tab while two callbacks wait","width":1280,"height":800,"caption":"Two callbacks wait: one for the timer, one for the promise."},{"t":"p","text":["In ",{"t":"ui","text":"Queues"},", each waiting callback is shown as a ",{"t":"strong","text":"chip"},": a small label that names what will run, such as \"setTimeout 10 ms\". The chips are grouped by queue."]},{"t":"h","level":2,"id":"step-through-it","text":"Step through it"},{"t":"p","text":["Go back to the start with ",{"t":"ui","text":"Go to the start"},", then press ",{"t":"ui","text":"Forward one step"}," until the run ends. Read the note of each step. Here is what you see:"]},{"t":"list","ordered":true,"items":[["The script runs from top to bottom first. It prints the first line. Nothing is waiting yet."],["The script asks for a 10 ms timer and a promise callback. Neither runs yet. ",{"t":"ui","text":"Queues"}," shows a chip for each: the timer under Timers, the promise callback under Microtask queue."],["The script has ended. At once, the promise callback runs and prints the second line. The timer still waits: its 10 ms have not passed."],["When 10 ms have passed, the event loop reaches its timers phase and runs the timer's callback. It prints the last line. Nothing is left to wait for, and the program ends."]]},{"t":"h","level":2,"id":"why-the-promise-went-first","text":"Why the promise went first"},{"t":"p","text":["A promise callback is a microtask: a small task that runs as soon as the JavaScript that is running now has finished, before the event loop goes on. Here, the JavaScript running was the script itself."]},{"t":"p","text":["A timer's callback waits for two things: for the event loop to come round to its timers phase, and for its own time to have come."]},{"t":"p","text":["So the promise callback ran before the timer, even though the timer was asked for first. Later lessons go through both queues in detail."]},{"t":"note","kind":"tip","text":["If you remember one thing: code that is scheduled for later runs later, when Node takes it out of a queue, rather than where it is written. ",{"t":"ui","text":"Queues"}," shows those queues."]},{"t":"check","question":["Change the timer's delay to 0 ms: ",{"t":"code","text":"setTimeout(..., 0)"},". Which line comes second now?"],"answer":["Still the promise callback. A promise callback is a microtask: it runs as soon as the script has finished. A timer, even a 0 ms one, waits for the event loop."]}],"examples":{"first-run":{"id":"first-run","title":"One timer, one promise, three lines","name":"first-run.js","module":"commonjs","text":"// Your first program in nodejs-map: one timer, one promise, three lines of output.\nconsole.log('1. the script starts');\n\nsetTimeout(() => {\n console.log('3. the timer fires');\n}, 10);\n\nPromise.resolve().then(() => {\n console.log('2. the promise callback runs');\n});\n","racy":false,"output":["1. the script starts","2. the promise callback runs","3. the timer fires"],"recording":"rec/first-run.nmrec.gz","steps":[{"index":16,"title":"The script starts","text":"The first line of the program runs and prints. The main thread is running the script, and nothing is waiting yet."},{"index":27,"title":"Two things wait","text":"The script has asked for a timer and a promise callback. Queues lists \"setTimeout 10 ms\" under Timers and \"promise reaction\" under Microtask queue."},{"index":31,"title":"The promise callback runs","text":"The script has finished, so the promise callback runs at once. The timer is still waiting: its 10 ms have not passed yet."},{"index":49,"title":"The timer fires","text":"When 10 ms have passed, the event loop reaches its timers phase, and the timer's callback prints the last line. Then nothing is left to wait for, and the program ends."}]}},"prev":{"id":"big-picture","title":"Node.js under the hood: the big picture"},"next":{"id":"glossary","title":"Glossary"}}
@@ -0,0 +1 @@
1
+ {"id":"follow-readfile","chapter":"under-the-hood","title":"Following one fs.readFile through lib/, src/, libuv and back","summary":"Walk the call path of fs.readFile stop by stop, from JavaScript through the C++ binding onto a pool thread and back to your callback.","blocks":[{"t":"p","text":["By the end of this lesson you can name the main functions a small ",{"t":"code","text":"fs.readFile"}," passes through in Node 26.13.1, in which layer each one lives, and on which thread each runs."]},{"t":"h","level":2,"id":"the-run","text":"The run"},{"t":"example","example":"readfile-thread-pool"},{"t":"p","text":["Open ",{"t":"ui","text":"Call paths"}," and choose ",{"t":"path","id":"p:fs-readFile","text":"fs.readFile(path, callback): to the thread pool and back"},". Each stop opens its lines in ",{"t":"ui","text":"Source"},", which links to the same lines on GitHub, at the exact commit of Node 26.13.1. The path is marked as a model: it was traced by hand from the source code, and shows what the code does, not what one run reported."]},{"t":"h","level":2,"id":"the-layers-in-order","text":"The layers, in order"},{"t":"list","ordered":true,"items":[[{"t":"strong","text":"lib/"}," (JavaScript, main thread). ",{"t":"code","text":"fs.readFile"}," in ",{"t":"code","text":"lib/fs.js"}," checks its arguments and, through the C++ binding, creates a ",{"t":"code","text":"ReadFileJob"},": one job that will do the whole read."],[{"t":"strong","text":"src/"}," (C++, main thread). ",{"t":"code","text":"job.run(path)"}," checks permissions, and ",{"t":"code","text":"ThreadPoolWork::ScheduleWork"}," hands the job to libuv with ",{"t":"code","text":"uv_queue_work"},"."],[{"t":"strong","text":"libuv"}," (C, main thread). ",{"t":"code","text":"uv__work_submit"}," puts the job on the thread pool's single queue and wakes a thread. The first use of the pool creates its threads."],[{"t":"strong","text":"libuv"}," (C, a pool thread). A pool thread takes the job and runs ",{"t":"code","text":"ReadFileJob::DoThreadPoolWork"},": open, fstat, read and close, one after the other, as blocking calls. Then it puts the finished job on the loop's done list and wakes the loop."],[{"t":"strong","text":"libuv"}," (main thread). The event loop notices the wake-up. On Unix that happens inside the poll step; on Windows the result is handled right after poll. ",{"t":"code","text":"uv__work_done"}," runs the job's \"after\" function."],[{"t":"strong","text":"src/"}," and ",{"t":"strong","text":"lib/"}," (main thread). The C++ side turns the result into a JavaScript value and calls back into ",{"t":"code","text":"lib/fs.js"},", which calls your callback. Then the nextTick and microtask queues are emptied, as after every callback."]]},{"t":"note","kind":"honest","text":["The run reports some of these stops and leaves the rest to the map. async_hooks reports the request being created (stop 1) and your callback starting and ending (stop 6). Trace events report the job being handed to the pool (stop 2), its result being delivered (stop 5), and the pool thread starting and finishing the job (stop 4). The pool thread's reports arrive late on the official build, and which job a thread ran is worked out from their order. The stops in between are what the code does, traced from the source and shown on the map."]},{"t":"check","question":["On which thread do the ",{"t":"code","text":"open"}," and ",{"t":"code","text":"read"}," system calls of a small ",{"t":"code","text":"fs.readFile"}," run, and on which thread does your callback run?"],"answer":["The system calls run on a thread pool thread; your callback runs on the main thread, after the event loop has picked up the finished job."]}],"examples":{"readfile-thread-pool":{"id":"readfile-thread-pool","title":"Reading a file: one trip through the thread pool","name":"readfile-callback.js","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,"output":["sync: after calling readFile","nextTick","readFile callback: err=null text=hello world"],"recording":"rec/readfile-thread-pool.nmrec.gz","steps":[{"index":25,"title":"One job for the pool","text":"fs.readFile created a request, the \"fs.readFile\" chip, and handed one job to the thread pool. Open the Thread pool tab."},{"index":30,"title":"A pool thread starts it","text":"A pool thread reported starting an \"fs.readfile\" job (observed). That it is this job is inferred. Reports from pool threads reach nodejs-map late, so where they sit against the main thread is approximate."},{"index":34,"title":"The thread is done","text":"The pool thread has finished. Open, read and close all happened there, in one job. The result now waits under \"Finished, not delivered\" until the main thread is free and the loop picks it up."},{"index":54,"title":"The callback runs","text":"The loop delivers the result, and the callback runs on the main thread. The script's last line and the tick came earlier, as always. On Windows this happens in the pending phase right after poll; Node did not report the phase, so it is marked inferred."}]}},"prev":{"id":"observed-and-inferred","title":"How the tool knows what it shows"},"next":{"id":"one-libuv-timer","title":"How all your timers sit on one libuv timer"}}
@@ -0,0 +1 @@
1
+ {"id":"four-threads-six-jobs","chapter":"thread-pool","title":"The thread pool: four threads, six jobs","summary":"Six CPU-heavy crypto jobs on the default pool of four threads. Four start at once; two wait for a free thread.","blocks":[{"t":"p","text":["By the end of this lesson you can explain what happens when a program asks for more pool work than there are threads."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"pbkdf2-six-jobs-four-threads"},{"t":"p","text":[{"t":"code","text":"crypto.pbkdf2"}," computes a password hash. It is slow on purpose, and Node runs it on the thread pool. The program starts six of them at once."]},{"t":"h","level":2,"id":"what-you-saw","text":"What you saw"},{"t":"list","ordered":false,"items":[["The pool has four threads by default. Jobs 1 to 4 each get a thread right away."],["Jobs 5 and 6 wait under \"Waiting for a thread\" in ",{"t":"ui","text":"Thread pool"},"."],["When a thread finishes a job, it takes the next waiting job. The pool has one queue, first in, first out."],["So the results come in two waves. The second wave comes about one job's time after the first."]]},{"t":"p","text":["The main thread is free the whole time: the hashing happens on the pool threads. The main thread is busy only for a moment each time a result is delivered."]},{"t":"p","text":["To see the code behind it, open ",{"t":"ui","text":"Call paths"}," and choose ",{"t":"path","id":"p:crypto-pbkdf2","text":"crypto.pbkdf2(...): a CPU job on the thread pool"},"."]},{"t":"note","kind":"honest","text":["Which finished job is delivered first is a race between threads. In most runs jobs 1 to 4 finish first; sometimes a thread starts late and the waves split differently. The recording shows one run."]},{"t":"check","question":["Your server hashes a password with ",{"t":"code","text":"crypto.pbkdf2"}," for every login. Eight users log in at the same moment. What do the last four wait for?"],"answer":["For a free pool thread: with the default pool of four threads, four hashes run and four wait in the pool's queue."]}],"examples":{"pbkdf2-six-jobs-four-threads":{"id":"pbkdf2-six-jobs-four-threads","title":"Six pbkdf2 jobs on four threads","name":"threadpool-pbkdf2.js","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,"output":["queued 6 jobs","wave 1 done: 1 2 3 4","wave 2 done: 5 6"],"recording":"rec/pbkdf2-six-jobs-four-threads.nmrec.gz","steps":[{"index":42,"title":"Four threads, four jobs","text":"Jobs 1 to 4 each got a pool thread right away. The Thread pool tab shows all four threads busy, each with a \"crypto.pbkdf2\" request."},{"index":50,"title":"Jobs 5 and 6 wait","text":"Jobs 5 and 6 were handed over too, but every thread is busy, so they wait under \"Waiting for a thread\". That a job was handed to the pool is inferred from the request Node created."},{"index":67,"title":"A thread finishes...","text":"Then the first thread finished its job. Each of these hashes keeps a thread busy for a while, and nothing else runs on that thread meanwhile."},{"index":69,"title":"...and takes job 5","text":"The same thread picked up job 5 straight away. The pool has one queue, first in, first out, so the waiting jobs start in the order they were handed over."},{"index":74,"title":"The first result comes back","text":"The finished job's callback runs on the main thread (on Windows in the pending phase after poll; inferred)."},{"index":113,"title":"Wave 1","text":"Four results are in: jobs 1 to 4, which started first."},{"index":144,"title":"Wave 2, one job later","text":"Jobs 5 and 6 finish about one job's time after the others, because they had to wait for a free thread."}]}},"prev":{"id":"reading-a-file","title":"Reading a file: one trip through the thread pool"},"next":{"id":"pool-size","title":"Changing the pool size"}}
@@ -0,0 +1 @@
1
+ {"id":"glossary","chapter":"before","title":"Glossary","summary":"Every word about Node's insides or about nodejs-map that this course uses, in a sentence or two, with a link to the lesson that introduces it.","blocks":[{"t":"p","text":["This page lists every word about Node's insides, or about nodejs-map, that the course uses. Each entry says it in a sentence or two and links to the lesson that introduces it. Come back here whenever a word is unclear."]},{"t":"p","text":["Read it whenever you need it: many entries belong to later chapters."]},{"t":"h","level":2,"id":"the-tool","text":"The tool"},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"recording"},": a list of everything Node reported during one run, in order, with the time of each report. It is data, not code. ",{"t":"link","text":"What nodejs-map is","href":"learn:what-it-is"}],[{"t":"strong","text":"replay"},": playing a recording back at a speed you choose. It shows the recorded run again, as often as you like. ",{"t":"link","text":"What nodejs-map is","href":"learn:what-it-is"}],[{"t":"strong","text":"local app"},": nodejs-map started on your computer with ",{"t":"code","text":"npx nodejs-map"},". It can run your programs. ",{"t":"link","text":"What nodejs-map is","href":"learn:what-it-is"}],[{"t":"strong","text":"player website"},": nodejs-map as a public web page. It opens recordings, on any computer or phone. ",{"t":"link","text":"What nodejs-map is","href":"learn:what-it-is"}],[{"t":"strong","text":"observed"},": the mark of a fact that Node itself reported. ",{"t":"link","text":"A tour of the screen","href":"learn:tour"}],[{"t":"strong","text":"inferred"},": the mark of a fact that nodejs-map worked out from what Node reported, by a written rule. ",{"t":"link","text":"A tour of the screen","href":"learn:tour"}],[{"t":"strong","text":"model"},": the mark of a drawing that explains how something works in general, rather than a measurement of your own run. ",{"t":"link","text":"A tour of the screen","href":"learn:tour"}],[{"t":"strong","text":"chip"},": a small label in the Queues tab for one waiting callback, such as \"setTimeout 10 ms\". ",{"t":"link","text":"Your first run","href":"learn:first-run"}],[{"t":"strong","text":"rule"},": the written explanation behind an inferred fact: what was seen, what is concluded, on which systems, and which lines of Node's source code it relies on. ",{"t":"link","text":"The three marks","href":"learn:three-marks"}],[{"t":"strong","text":"call path"},": a list of the functions that one call goes through inside Node, traced by hand from the source code and drawn on the map. ",{"t":"link","text":"The map","href":"learn:the-map"}],[{"t":"strong","text":"breakpoint"},": a mark on a line of your program. The program stops when it reaches that line, before running it. ",{"t":"link","text":"Stopping at a line","href":"learn:breakpoints"}],[{"t":"strong","text":"step over"},": while stopped, run the current statement, including any function it calls, and stop at the next one. ",{"t":"link","text":"Stopping at a line","href":"learn:breakpoints"}],[{"t":"strong","text":"step into"},": while stopped, go into the function the current statement calls, and stop at its first statement. ",{"t":"link","text":"Stopping at a line","href":"learn:breakpoints"}],[{"t":"strong","text":"step out"},": while stopped, run the rest of the current function, and stop right after the place that called it. ",{"t":"link","text":"Stopping at a line","href":"learn:breakpoints"}],[{"t":"strong","text":"race"},": two things that can finish in either order, depending on timing. ",{"t":"link","text":"Stopping at a line","href":"learn:breakpoints"}],[{"t":"strong","text":"async item"},": nodejs-map's name for anything Node tracks that can call back later, such as a timer, a request or a promise. ",{"t":"link","text":"An HTTP server and one request","href":"learn:http-one-request"}],[{"t":"strong","text":"async_hooks"},": a module of Node that tells nodejs-map when something that can call back is created, when its callback starts and ends, and when a promise settles. ",{"t":"link","text":"How the tool knows","href":"learn:observed-and-inferred"}],[{"t":"strong","text":"trace event"},": a timed report from Node's own C++ code, such as \"running timers now\", or work starting on a pool thread. ",{"t":"link","text":"How the tool knows","href":"learn:observed-and-inferred"}],[{"t":"strong","text":"probe build"},": a specially patched Node that reports the event loop directly and can stop it between phases. It runs on Linux today. ",{"t":"link","text":"How the tool knows","href":"learn:observed-and-inferred"}],[{"t":"strong","text":"gate"},": a place where the probe build's event loop stops and waits for a click. ",{"t":"link","text":"The probe build","href":"learn:probe-build"}]]},{"t":"h","level":2,"id":"node-s-parts","text":"Node's parts"},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"thread"},": one line of work inside a running program. A program can have several, running at the same time. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"main thread"},": the one thread on which Node runs all of your JavaScript, and the event loop. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"V8"},": the JavaScript engine inside Node, the same as in Chrome. It runs the JavaScript language itself; files, timers and sockets come from Node. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"Node's JavaScript library"},": the modules like ",{"t":"code","text":"fs"},", ",{"t":"code","text":"http"}," and ",{"t":"code","text":"timers"},", written in JavaScript, in the ",{"t":"code","text":"lib/"}," folder of Node's source code. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"binding"},": a C++ function that Node's JavaScript library can call as if it were JavaScript. Bindings live in the ",{"t":"code","text":"src/"}," folder. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"libuv"},": the C library that Node uses for everything that waits: files, network connections, timers. It contains the event loop and the thread pool. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"event loop"},": the loop in libuv, on the main thread, that looks at what has finished or become due and calls back into JavaScript, one callback at a time. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"phase"},": one of the fixed stops of each turn of the event loop, such as the timers phase. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"turn"},": one time round the event loop, through all its phases. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"thread pool"},": a few extra threads in libuv, four by default, that do slow work such as reading files away from the main thread. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"handle"},": something long-lived in libuv that can call back many times: a timer, a server, a connection. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"request"},": a one-off piece of work in libuv that calls back once, such as reading a file. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"queue"},": a waiting line: the first to join is the first to leave. Node keeps callbacks that are ready to run in several queues. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"callback queue"},": a name some articles use for Node's waiting lines as a whole. Node keeps several, one per kind of callback. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}],[{"t":"strong","text":"microtask"},": a small job, such as a promise callback, that runs as soon as the JavaScript running now has finished. Microtasks wait in V8's microtask queue. ",{"t":"link","text":"The big picture","href":"learn:big-picture"}]]},{"t":"h","level":2,"id":"the-event-loop","text":"The event loop"},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"call stack"},": the functions that are running right now, each one called by the one below it. ",{"t":"link","text":"One thing at a time","href":"learn:call-stack"}],[{"t":"strong","text":"run to completion"},": each piece of JavaScript runs until it returns; Node starts the next one only then. ",{"t":"link","text":"One thing at a time","href":"learn:call-stack"}],[{"t":"strong","text":"due time"},": the moment a timer's delay is over. The timer runs at that moment or after it. ",{"t":"link","text":"What a delay really means","href":"learn:timers-are-not-now"}],[{"t":"strong","text":"nextTick"},": ",{"t":"code","text":"process.nextTick(fn)"}," puts ",{"t":"code","text":"fn"}," in Node's nextTick queue, which is emptied as soon as the current JavaScript has finished, before the microtask queue. One such callback is a tick. ",{"t":"link","text":"process.nextTick","href":"learn:next-tick"}],[{"t":"strong","text":"macrotask"},": a name for a callback that the event loop itself runs, such as a timer or an I/O result, as opposed to ticks and microtasks. ",{"t":"link","text":"The order","href":"learn:order-and-esm"}],[{"t":"strong","text":"poll"},": the phase in which libuv asks the operating system what has finished, and waits when nothing is due. ",{"t":"link","text":"The phases","href":"learn:loop-phases"}],[{"t":"strong","text":"pending"},": the phase for callbacks that libuv put off; on Windows, I/O callbacks run there right after poll. ",{"t":"link","text":"The phases","href":"learn:loop-phases"}],[{"t":"strong","text":"check phase"},": the phase that runs ",{"t":"code","text":"setImmediate"}," callbacks. ",{"t":"link","text":"The phases","href":"learn:loop-phases"}],[{"t":"strong","text":"close phase"},": the phase that runs callbacks for closed handles, such as a socket's ",{"t":"code","text":"'close'"}," event. ",{"t":"link","text":"The phases","href":"learn:loop-phases"}],[{"t":"strong","text":"unref"},": ",{"t":"code","text":"timer.unref()"}," tells Node to leave that timer out of the count when it decides whether to keep the process alive. ",{"t":"link","text":"What keeps a process alive","href":"learn:staying-alive"}]]},{"t":"h","level":2,"id":"work-off-the-main-thread","text":"Work off the main thread"},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"job"},": a piece of work handed to the thread pool. ",{"t":"link","text":"Reading a file","href":"learn:reading-a-file"}],[{"t":"strong","text":"blocking"},": JavaScript that runs for a long time blocks the event loop: nothing else in the process can run until it returns. ",{"t":"link","text":"Blocking the loop","href":"learn:blocking-the-loop"}],[{"t":"strong","text":"worker thread"},": a thread from Node's ",{"t":"code","text":"worker_threads"}," module that runs JavaScript with its own event loop. ",{"t":"link","text":"Blocking the loop","href":"learn:blocking-the-loop"}]]},{"t":"h","level":2,"id":"networking-and-streams","text":"Networking and streams"},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"parser"},": the code in Node's HTTP module that reads the text of HTTP and turns it into request and response objects. ",{"t":"link","text":"An HTTP server and one request","href":"learn:http-one-request"}],[{"t":"strong","text":"keep-alive"},": keeping a TCP connection open after an HTTP response, so the next request can use it. ",{"t":"link","text":"Keep-alive","href":"learn:keep-alive"}],[{"t":"strong","text":"stream"},": an object that hands over data a piece at a time: readable, writable, or both (a transform). ",{"t":"link","text":"Streams","href":"learn:streams-basics"}],[{"t":"strong","text":"chunk"},": one piece of data in a stream. ",{"t":"link","text":"Streams","href":"learn:streams-basics"}],[{"t":"strong","text":"backpressure"},": a slow destination pushing back on a fast source: ",{"t":"code","text":"write()"}," returns false, and the source waits for ",{"t":"code","text":"'drain'"},". ",{"t":"link","text":"Backpressure","href":"learn:backpressure"}],[{"t":"strong","text":"highWaterMark"},": the amount of waiting data at which a writable stream's ",{"t":"code","text":"write()"}," starts returning false. ",{"t":"link","text":"Backpressure","href":"learn:backpressure"}]]},{"t":"check","question":["You meet the word \"phase\" in a lesson and are not sure what it means. Where do you look?"],"answer":["Here, in the Glossary: a phase is one of the fixed stops of each turn of the event loop. The link takes you to the big-picture lesson that introduces it."]}],"examples":{},"prev":{"id":"first-run","title":"Your first run"},"next":{"id":"playback","title":"Watching a run, step by step"}}
@@ -0,0 +1 @@
1
+ {"id":"hiding-areas","chapter":"before","title":"Showing just the areas you need","summary":"Keep the areas a lesson uses, hide the rest with one click, and bring them back the same way.","blocks":[{"t":"p","text":["By the end of this lesson you can hide any area of the screen and bring it back."]},{"t":"h","level":2,"id":"why-hide-areas","text":"Why hide areas"},{"t":"p","text":["The screen shows a lot at once. In the first lessons you use the code panel, two tabs of the panels, and the playback bar. The map can wait."]},{"t":"p","text":["Hiding the map gives the other areas more room and keeps the screen simple."]},{"t":"h","level":2,"id":"the-view-menu","text":"The View menu"},{"t":"p","text":["Click ",{"t":"ui","text":"View"}," in the top bar. The menu lists the four areas: ",{"t":"ui","text":"Map"},", ",{"t":"ui","text":"Code"},", ",{"t":"ui","text":"Panels"}," and ",{"t":"ui","text":"Playback bar"},"."]},{"t":"p","text":["Click an area in the menu to hide it. Click it again to show it."]},{"t":"image","src":"img/hide-view-menu.webp","alt":"The View menu, open","width":1280,"height":800,"caption":"The View menu lists the four areas of the screen."},{"t":"p","text":["The keyboard does the same: ",{"t":"kbd","text":"Alt+1"}," for the map, ",{"t":"kbd","text":"Alt+2"}," for the code panel, ",{"t":"kbd","text":"Alt+3"}," for the panels and ",{"t":"kbd","text":"Alt+4"}," for the playback bar."]},{"t":"h","level":2,"id":"the-buttons","text":"The × buttons"},{"t":"p","text":["Each area also has its own × button: ",{"t":"ui","text":"Hide map"},", ",{"t":"ui","text":"Hide code"},", ",{"t":"ui","text":"Hide panels"}," and ",{"t":"ui","text":"Hide playback bar"},". One click hides that area."]},{"t":"h","level":2,"id":"bringing-an-area-back","text":"Bringing an area back"},{"t":"p","text":["A hidden area leaves a thin strip where it was: ",{"t":"ui","text":"Map hidden · Show"},", for example. Click Show on the strip, and the area comes back."]},{"t":"image","src":"img/hide-restore-strip.webp","alt":"The strip that the hidden map leaves behind","width":1280,"height":800,"caption":"Where the map was, a strip says that it is hidden."},{"t":"p","text":["One of the three main areas always stays open: the map, the code panel and the panels. The app keeps the last one of them open, and tells you so."]},{"t":"p","text":["Two more items in the View menu help when the screen looks wrong:"]},{"t":"list","ordered":false,"items":[[{"t":"ui","text":"Show all"}," shows every area again."],[{"t":"ui","text":"Reset layout"}," shows every area again, each at its first size."]]},{"t":"note","kind":"tip","text":["Hiding an area changes what is on the screen, and leaves the run itself untouched."]},{"t":"check","question":["You have hidden the map and the playback bar. Now you want everything back at once. What do you click?"],"answer":["The View button in the top bar, then Show all. Reset layout also works, and puts every area back at its first size too."]}],"examples":{},"prev":{"id":"tour","title":"A tour of the screen"},"next":{"id":"big-picture","title":"Node.js under the hood: the big picture"}}
@@ -0,0 +1 @@
1
+ {"id":"http-one-request","chapter":"networking","title":"An HTTP server and one request","summary":"An HTTP server is a TCP server plus code that reads and writes HTTP. Follow one request from the socket to your handler and back.","blocks":[{"t":"p","text":["By the end of this lesson you can say what Node's HTTP module adds on top of a TCP socket, and where your request handler runs."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"p","text":["Node's HTTP module has a ",{"t":"strong","text":"parser"},": the code that reads the text of HTTP, as it arrives on a socket, and turns it into request and response objects."]},{"t":"example","example":"http-roundtrip"},{"t":"p","text":["A server, one ",{"t":"code","text":"GET /hi"}," request from the same program, and a clean shutdown."]},{"t":"h","level":2,"id":"what-http-adds","text":"What HTTP adds"},{"t":"list","ordered":false,"items":[["Underneath there is an ordinary TCP connection: a connect request in Pending I/O, and socket callbacks from the poll phase."],["When bytes arrive, the parser turns them into a request object, ",{"t":"code","text":"req"},", with its method, URL and headers. Then it calls your handler."],[{"t":"code","text":"req"}," lets you read the request body; ",{"t":"code","text":"res"}," lets you write the response. ",{"t":"code","text":"res.end('hello')"}," writes the status line, the headers and the body to the socket."],["On the client side the same happens the other way round. The parser reads the status line and the headers and calls the response callback. The body follows as ",{"t":"code","text":"'data'"}," events."]]},{"t":"p","text":["Open ",{"t":"ui","text":"Stack"}," while your handler runs. It shows the handler running inside a callback of type HTTPINCOMINGMESSAGE. That is an ",{"t":"strong","text":"async item"},": nodejs-map's name for anything Node tracks that can call back later, such as a timer, a request or a promise. Its type is the name Node gives it."]},{"t":"h","level":2,"id":"timers-the-server-sets-for-you","text":"Timers the server sets for you"},{"t":"p","text":["Look at ",{"t":"ui","text":"Queues"},": there is a \"setInterval 30000 ms\" timer you never set. It is the server's own check for requests that take too long to arrive. It is unref'd, so the process can still exit while it waits. HTTP also sets timers of its own for sockets that stay quiet too long."]},{"t":"note","kind":"honest","text":["nodejs-map shows HTTP as what it is underneath: sockets, timers and callbacks. A view made for requests and responses themselves is still to come."]},{"t":"check","question":["Your handler calls ",{"t":"code","text":"res.end()"}," and returns. Has the client received the response at that moment?"],"answer":["No. ",{"t":"code","text":"res.end()"}," hands the bytes to the socket. They reach the client through the operating system, and the client's callbacks run later, in the poll phase of a later turn."]}],"examples":{"http-roundtrip":{"id":"http-roundtrip","title":"An HTTP server and one request","name":"http-roundtrip.js","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,"output":["server: listening","server: GET /hi","client: status 200","client: body hello","server: closed"],"recording":"rec/http-roundtrip.nmrec.gz","steps":[{"index":75,"title":"The request arrives","text":"Node's HTTP parser has turned the bytes from the socket into a request object, and your handler runs. The Stack tab shows it running inside a callback of type HTTPINCOMINGMESSAGE."},{"index":130,"title":"The response reaches the client","text":"The client's response callback runs when the status line and headers have been parsed; the body comes after."},{"index":175,"title":"Closed","text":"After the body, the client closes the server and the process ends."}]}},"prev":{"id":"many-clients","title":"Many clients on one thread"},"next":{"id":"http-two-requests","title":"Two overlapping requests"}}
@@ -0,0 +1 @@
1
+ {"id":"http-two-requests","chapter":"networking","title":"Two overlapping requests","summary":"While one handler waits for a timer, a file or a database, the event loop answers other requests: waiting leaves the main thread free.","blocks":[{"t":"p","text":["By the end of this lesson you can explain why a fast request is answered while a slow one is still waiting."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"http-two-requests"},{"t":"p","text":["The server answers ",{"t":"code","text":"/slow"}," after a 50 ms timer and ",{"t":"code","text":"/fast"}," at once. The client asks for ",{"t":"code","text":"/slow"}," first."]},{"t":"h","level":2,"id":"what-you-saw","text":"What you saw"},{"t":"list","ordered":false,"items":[["The ",{"t":"code","text":"/slow"}," handler sets a timer and returns without answering. The request stays open, but the main thread is free."],["The ",{"t":"code","text":"/fast"}," request is read and answered while the timer still waits under Timers."],["When the timer fires, the ",{"t":"code","text":"/slow"}," handler's timer callback answers it."]]},{"t":"p","text":["Most real servers work like this: their handlers wait for a database, a file or another service, and while one waits, the event loop serves others."]},{"t":"note","kind":"tip","text":["\"Waiting\" means a timer, a socket, or a thread pool job is in charge until the answer comes. \"Computing\" means your JavaScript is running. Only computing blocks other requests."]},{"t":"check","question":["Replace the 50 ms timer with a loop that computes for 50 ms. Which response does the client get first now?"],"answer":["Most likely ",{"t":"code","text":"/slow"},": if its handler runs first, the loop occupies the main thread for 50 ms and ",{"t":"code","text":"/fast"}," cannot even be read before it ends. The next lesson shows this."]}],"examples":{"http-two-requests":{"id":"http-two-requests","title":"A slow request does not hold up a fast one","name":"http-two-requests.js","module":"commonjs","text":"// Two requests at once: a slow one (waits on a timer) does not hold up a fast one.\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n if (req.url === '/slow') setTimeout(() => res.end('slow'), 50);\n else res.end('fast');\n});\n\nserver.listen(0, '127.0.0.1', () => {\n let left = 2;\n for (const path of ['/slow', '/fast']) {\n http.get({ host: '127.0.0.1', port: server.address().port, path, agent: false }, (res) => {\n res.setEncoding('utf8');\n res.on('data', (body) => console.log('client got ' + body));\n res.on('end', () => {\n if (--left === 0) server.close();\n });\n });\n }\n});\n","racy":false,"output":["client got fast","client got slow"],"recording":"rec/http-two-requests.nmrec.gz","steps":[{"index":92,"title":"/slow waits on a timer","text":"The /slow handler set a \"setTimeout 50 ms\" timer and returned without answering. The main thread is free again."},{"index":163,"title":"/fast is answered meanwhile","text":"The /fast request is answered while the 50 ms timer is still waiting under Timers."},{"index":262,"title":"/slow is answered","text":"About 50 ms later the timer fires, and only then is /slow answered."}]}},"prev":{"id":"http-one-request","title":"An HTTP server and one request"},"next":{"id":"keep-alive","title":"Keep-alive"}}
Binary file
Binary file
Binary file