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,390 @@
1
+ {
2
+ "version": 1,
3
+ "chapters": [
4
+ {
5
+ "id": "before",
6
+ "title": "Before you start",
7
+ "summary": "What nodejs-map is, what you need to know first, a tour of the screen, the parts of Node.js in one picture, and your first run.",
8
+ "lessons": [
9
+ {
10
+ "id": "what-it-is",
11
+ "title": "What nodejs-map is",
12
+ "summary": "A tool that runs your Node.js program on your own computer and shows what happens inside Node while it runs.",
13
+ "minutes": 4,
14
+ "level": "start",
15
+ "file": "what-it-is.json"
16
+ },
17
+ {
18
+ "id": "prerequisites",
19
+ "title": "What you need to know, and what you need installed",
20
+ "summary": "The JavaScript and Node.js this course takes for granted, what it explains for you, what to install, and how to start nodejs-map.",
21
+ "minutes": 5,
22
+ "level": "start",
23
+ "file": "prerequisites.json"
24
+ },
25
+ {
26
+ "id": "tour",
27
+ "title": "A tour of the screen",
28
+ "summary": "The main areas of nodejs-map, each named on one picture, with what each one is for.",
29
+ "minutes": 4,
30
+ "level": "start",
31
+ "file": "tour.json"
32
+ },
33
+ {
34
+ "id": "hiding-areas",
35
+ "title": "Showing just the areas you need",
36
+ "summary": "Keep the areas a lesson uses, hide the rest with one click, and bring them back the same way.",
37
+ "minutes": 2,
38
+ "level": "start",
39
+ "file": "hiding-areas.json"
40
+ },
41
+ {
42
+ "id": "big-picture",
43
+ "title": "Node.js under the hood: the big picture",
44
+ "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.",
45
+ "minutes": 9,
46
+ "level": "start",
47
+ "file": "big-picture.json"
48
+ },
49
+ {
50
+ "id": "first-run",
51
+ "title": "Your first run",
52
+ "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.",
53
+ "minutes": 5,
54
+ "level": "start",
55
+ "file": "first-run.json"
56
+ },
57
+ {
58
+ "id": "glossary",
59
+ "title": "Glossary",
60
+ "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.",
61
+ "minutes": 5,
62
+ "level": "start",
63
+ "file": "glossary.json"
64
+ }
65
+ ]
66
+ },
67
+ {
68
+ "id": "start",
69
+ "title": "Using the tool",
70
+ "summary": "Move through a recorded run, read the three marks, find things on the map, stop a program at a line, and save or share a run.",
71
+ "lessons": [
72
+ {
73
+ "id": "playback",
74
+ "title": "Watching a run, step by step",
75
+ "summary": "Play a run fast or slowly, step through it, jump with the timeline, and know what a replay tells you.",
76
+ "minutes": 5,
77
+ "level": "start",
78
+ "file": "playback.json"
79
+ },
80
+ {
81
+ "id": "three-marks",
82
+ "title": "The three marks: observed, inferred, model",
83
+ "summary": "Every fact on the screen says how nodejs-map knows it. Read the three marks on a real run, and learn when to trust what.",
84
+ "minutes": 6,
85
+ "level": "start",
86
+ "file": "three-marks.json"
87
+ },
88
+ {
89
+ "id": "the-map",
90
+ "title": "The map: where in Node is this?",
91
+ "summary": "Move and zoom on the map of Node, open the source code behind a box, and follow one call from your code down into Node.",
92
+ "minutes": 6,
93
+ "level": "start",
94
+ "file": "the-map.json"
95
+ },
96
+ {
97
+ "id": "breakpoints",
98
+ "title": "Stopping at a line, and stepping",
99
+ "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.",
100
+ "minutes": 7,
101
+ "level": "start",
102
+ "file": "breakpoints.json"
103
+ },
104
+ {
105
+ "id": "save-and-share",
106
+ "title": "Saving, opening and sharing a run",
107
+ "summary": "Keep a run as a file, open it again anywhere, and send it to someone as a file or a link. A recording is data, so opening one is always safe.",
108
+ "minutes": 4,
109
+ "level": "start",
110
+ "file": "save-and-share.json"
111
+ }
112
+ ]
113
+ },
114
+ {
115
+ "id": "event-loop",
116
+ "title": "The event loop",
117
+ "summary": "How Node decides what runs next: one callback at a time, timers, process.nextTick, promises, the phases of the loop, and what keeps a process alive.",
118
+ "lessons": [
119
+ {
120
+ "id": "call-stack",
121
+ "title": "One thing at a time, to the end",
122
+ "summary": "Node runs one piece of JavaScript at a time, to its end. A timer that becomes due in the middle waits its turn.",
123
+ "minutes": 6,
124
+ "level": "core",
125
+ "file": "call-stack.json"
126
+ },
127
+ {
128
+ "id": "timers-are-not-now",
129
+ "title": "What a delay really means",
130
+ "summary": "A delay is a minimum, 0 ms means 1 ms, timers run in order of when they are due, and a busy main thread makes them late.",
131
+ "minutes": 7,
132
+ "level": "core",
133
+ "file": "timers-are-not-now.json"
134
+ },
135
+ {
136
+ "id": "next-tick",
137
+ "title": "process.nextTick",
138
+ "summary": "A process.nextTick callback runs as soon as the current JavaScript has finished, before promise callbacks, timers and I/O. Its queue is emptied completely each time.",
139
+ "minutes": 6,
140
+ "level": "core",
141
+ "file": "next-tick.json"
142
+ },
143
+ {
144
+ "id": "promises-and-microtasks",
145
+ "title": "Promises and microtasks",
146
+ "summary": "Promise callbacks and queueMicrotask share one queue, the microtask queue. Node empties it completely after the nextTick queue, before the event loop moves on.",
147
+ "minutes": 6,
148
+ "level": "core",
149
+ "file": "promises-and-microtasks.json"
150
+ },
151
+ {
152
+ "id": "async-await",
153
+ "title": "async/await is promises",
154
+ "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.",
155
+ "minutes": 7,
156
+ "level": "core",
157
+ "file": "async-await.json"
158
+ },
159
+ {
160
+ "id": "order-and-esm",
161
+ "title": "The order: ticks, microtasks, then the loop, and the ES module twist",
162
+ "summary": "After every callback Node empties the nextTick queue, then the microtask queue, before the event loop goes on. In an ES module the top level is itself a microtask, which swaps ticks and promises.",
163
+ "minutes": 7,
164
+ "level": "core",
165
+ "file": "order-and-esm.json"
166
+ },
167
+ {
168
+ "id": "loop-phases",
169
+ "title": "The phases of the event loop, one by one",
170
+ "summary": "Each turn of the event loop visits its phases in a fixed order. One tiny program per phase, and exactly where Windows differs from Linux and macOS.",
171
+ "minutes": 12,
172
+ "level": "core",
173
+ "file": "loop-phases.json"
174
+ },
175
+ {
176
+ "id": "timeout-vs-immediate",
177
+ "title": "setTimeout(0) or setImmediate?",
178
+ "summary": "From the script the two race, and either can win. Inside an I/O callback the immediate always wins. The order of the phases explains both.",
179
+ "minutes": 6,
180
+ "level": "core",
181
+ "file": "timeout-vs-immediate.json"
182
+ },
183
+ {
184
+ "id": "staying-alive",
185
+ "title": "What keeps a process alive",
186
+ "summary": "A Node process runs as long as something can still call back. Timers, sockets and requests keep it alive; unref lets one go; beforeExit and exit come at the end.",
187
+ "minutes": 7,
188
+ "level": "core",
189
+ "file": "staying-alive.json"
190
+ }
191
+ ]
192
+ },
193
+ {
194
+ "id": "thread-pool",
195
+ "title": "Work off the main thread",
196
+ "summary": "What the thread pool does, what uses it and what does not, and what slow JavaScript on the main thread does to everything else.",
197
+ "lessons": [
198
+ {
199
+ "id": "reading-a-file",
200
+ "title": "Reading a file: one trip through the thread pool",
201
+ "summary": "fs.readFile hands the whole read to a thread pool thread and comes back once. readFileSync does the same work on the main thread, and nothing else runs meanwhile.",
202
+ "minutes": 7,
203
+ "level": "core",
204
+ "file": "reading-a-file.json"
205
+ },
206
+ {
207
+ "id": "four-threads-six-jobs",
208
+ "title": "The thread pool: four threads, six jobs",
209
+ "summary": "Six CPU-heavy crypto jobs on the default pool of four threads. Four start at once; two wait for a free thread.",
210
+ "minutes": 6,
211
+ "level": "core",
212
+ "file": "four-threads-six-jobs.json"
213
+ },
214
+ {
215
+ "id": "pool-size",
216
+ "title": "Changing the pool size",
217
+ "summary": "UV_THREADPOOL_SIZE sets the number of pool threads, as long as it is set before the pool is first used.",
218
+ "minutes": 5,
219
+ "level": "core",
220
+ "file": "pool-size.json"
221
+ },
222
+ {
223
+ "id": "what-uses-the-pool",
224
+ "title": "What uses the thread pool",
225
+ "summary": "File system calls, dns.lookup, most crypto and zlib go to the pool. Timers and sockets stay on the main thread, and dns.lookup with an IP address answers straight away.",
226
+ "minutes": 7,
227
+ "level": "core",
228
+ "file": "what-uses-the-pool.json"
229
+ },
230
+ {
231
+ "id": "blocking-the-loop",
232
+ "title": "Blocking the loop with CPU work",
233
+ "summary": "CPU work in JavaScript runs on the main thread. While it runs, due timers and finished I/O wait, all of them.",
234
+ "minutes": 5,
235
+ "level": "core",
236
+ "file": "blocking-the-loop.json"
237
+ },
238
+ {
239
+ "id": "splitting-work",
240
+ "title": "Splitting work with setImmediate",
241
+ "summary": "Cut long work into slices and schedule each slice with setImmediate. Between slices the event loop runs timers and I/O.",
242
+ "minutes": 5,
243
+ "level": "core",
244
+ "file": "splitting-work.json"
245
+ }
246
+ ]
247
+ },
248
+ {
249
+ "id": "networking",
250
+ "title": "Networking",
251
+ "summary": "TCP and HTTP on your own machine, one callback at a time: connections, data, many clients, overlapping requests, keep-alive, and a handler that holds up everyone.",
252
+ "lessons": [
253
+ {
254
+ "id": "tcp-step-by-step",
255
+ "title": "A TCP server and client, step by step",
256
+ "summary": "listen, connect, data, end and close on 127.0.0.1, with the callback each one causes, the phase it runs in, and what waits in between.",
257
+ "minutes": 9,
258
+ "level": "core",
259
+ "file": "tcp-step-by-step.json"
260
+ },
261
+ {
262
+ "id": "many-clients",
263
+ "title": "Many clients on one thread",
264
+ "summary": "One server, three clients, one main thread. The event loop takes each ready socket in turn, and each callback runs on its own, one after another.",
265
+ "minutes": 6,
266
+ "level": "core",
267
+ "file": "many-clients.json"
268
+ },
269
+ {
270
+ "id": "http-one-request",
271
+ "title": "An HTTP server and one request",
272
+ "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.",
273
+ "minutes": 8,
274
+ "level": "core",
275
+ "file": "http-one-request.json"
276
+ },
277
+ {
278
+ "id": "http-two-requests",
279
+ "title": "Two overlapping requests",
280
+ "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.",
281
+ "minutes": 6,
282
+ "level": "core",
283
+ "file": "http-two-requests.json"
284
+ },
285
+ {
286
+ "id": "keep-alive",
287
+ "title": "Keep-alive",
288
+ "summary": "With keep-alive, a second HTTP request travels over the TCP connection that the first one opened, instead of opening a new one.",
289
+ "minutes": 5,
290
+ "level": "core",
291
+ "file": "keep-alive.json"
292
+ },
293
+ {
294
+ "id": "slow-handler",
295
+ "title": "A slow handler blocks everyone, and the fix",
296
+ "summary": "A handler that computes for 100 ms stops the whole server for 100 ms. Doing the same work in slices lets other requests through.",
297
+ "minutes": 8,
298
+ "level": "core",
299
+ "file": "slow-handler.json"
300
+ }
301
+ ]
302
+ },
303
+ {
304
+ "id": "streams",
305
+ "title": "Streams",
306
+ "summary": "Readable, writable and transform streams, backpressure, and how pipeline handles errors.",
307
+ "lessons": [
308
+ {
309
+ "id": "streams-basics",
310
+ "title": "Readable, writable, transform in ten lines",
311
+ "summary": "A readable stream produces chunks, a transform changes them, a writable consumes them. pipeline connects them and moves one chunk at a time.",
312
+ "minutes": 6,
313
+ "level": "deep",
314
+ "file": "streams-basics.json"
315
+ },
316
+ {
317
+ "id": "backpressure",
318
+ "title": "Backpressure made visible",
319
+ "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.",
320
+ "minutes": 6,
321
+ "level": "deep",
322
+ "file": "backpressure.json"
323
+ },
324
+ {
325
+ "id": "pipeline-errors",
326
+ "title": "pipeline and errors",
327
+ "summary": "pipeline reports the first error of any stream once, destroys every stream, and calls back. With files, the callback comes after the last file is closed.",
328
+ "minutes": 6,
329
+ "level": "deep",
330
+ "file": "pipeline-errors.json"
331
+ }
332
+ ]
333
+ },
334
+ {
335
+ "id": "under-the-hood",
336
+ "title": "Under the hood",
337
+ "summary": "How the tool knows what it shows, then calls followed through Node's own source code: where timers and microtasks really live, and how to step into Node's JavaScript.",
338
+ "lessons": [
339
+ {
340
+ "id": "observed-and-inferred",
341
+ "title": "How the tool knows what it shows",
342
+ "summary": "The three sources nodejs-map listens to on the official Node build, the rules that turn them into queues and phases, and the specially built Node used to check those rules.",
343
+ "minutes": 9,
344
+ "level": "deep",
345
+ "file": "observed-and-inferred.json"
346
+ },
347
+ {
348
+ "id": "follow-readfile",
349
+ "title": "Following one fs.readFile through lib/, src/, libuv and back",
350
+ "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.",
351
+ "minutes": 12,
352
+ "level": "deep",
353
+ "file": "follow-readfile.json"
354
+ },
355
+ {
356
+ "id": "one-libuv-timer",
357
+ "title": "How all your timers sit on one libuv timer",
358
+ "summary": "Node keeps your timers in JavaScript lists, one per duration, and gives libuv a single timer for the earliest of them.",
359
+ "minutes": 8,
360
+ "level": "deep",
361
+ "file": "one-libuv-timer.json"
362
+ },
363
+ {
364
+ "id": "microtasks-belong-to-v8",
365
+ "title": "The microtask queue belongs to V8",
366
+ "summary": "The nextTick queue is Node's, written in JavaScript; the microtask queue is V8's. Node decides when V8 empties it.",
367
+ "minutes": 8,
368
+ "level": "deep",
369
+ "file": "microtasks-belong-to-v8.json"
370
+ },
371
+ {
372
+ "id": "stepping-into-node",
373
+ "title": "Debugging Node's own JavaScript",
374
+ "summary": "Step from your code into node:internal files and watch Node's JavaScript library do its work, with the map following along.",
375
+ "minutes": 8,
376
+ "level": "deep",
377
+ "file": "stepping-into-node.json"
378
+ },
379
+ {
380
+ "id": "probe-build",
381
+ "title": "The probe build: stopping between phases",
382
+ "summary": "A patched Node build that reports the event loop from inside libuv and can stop it between phases, before a timer or before a pool job. On Linux today.",
383
+ "minutes": 7,
384
+ "level": "deep",
385
+ "file": "probe-build.json"
386
+ }
387
+ ]
388
+ }
389
+ ]
390
+ }
@@ -0,0 +1 @@
1
+ {"id":"keep-alive","chapter":"networking","title":"Keep-alive","summary":"With keep-alive, a second HTTP request travels over the TCP connection that the first one opened, instead of opening a new one.","blocks":[{"t":"p","text":["By the end of this lesson you can say what keeping a connection open between HTTP requests saves, and see it in a run."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"http-keep-alive"},{"t":"p","text":[{"t":"strong","text":"Keep-alive"}," means: when an HTTP response is complete, keep its TCP connection open, so that the next request to the same server can use it."]},{"t":"p","text":["The program sends two HTTP requests, one after the other, through an ",{"t":"code","text":"http.Agent"}," with ",{"t":"code","text":"keepAlive: true"},". An agent is the object that manages the client's connections. The server counts the connections it accepts."]},{"t":"h","level":2,"id":"what-you-saw","text":"What you saw"},{"t":"list","ordered":false,"items":[["The first request needs a connection: one connect request appears under Pending I/O."],["When the response is complete, the agent keeps the socket open and puts it in its pool of free sockets."],["The second request reuses it: no second connect request, and the server counts one connection."]]},{"t":"p","text":["In Node 26 the default agent, ",{"t":"code","text":"http.globalAgent"},", already has keep-alive on."]},{"t":"note","kind":"warn","text":["In the program the second request is sent from a ",{"t":"code","text":"setImmediate"},", not directly from the first response's ",{"t":"code","text":"'end'"}," callback. Sent directly from there, it found no free socket in this Node version and opened a second connection: the agent puts the socket back with a ",{"t":"code","text":"process.nextTick"}," queued at that moment, so it is not free yet while the callback runs."]},{"t":"note","kind":"honest","text":["Keep-alive sockets come with their own timers, which you will see under Timers with delays that Node chose for you. They close idle sockets after a while."]},{"t":"check","question":["Why does the program call ",{"t":"code","text":"agent.destroy()"}," before closing the server?"],"answer":["The kept-alive socket is still open and would keep the process alive; destroying the agent closes its free sockets."]}],"examples":{"http-keep-alive":{"id":"http-keep-alive","title":"Two requests over one connection","name":"http-keep-alive.js","module":"commonjs","text":"// Keep-alive: two requests one after the other travel over the same TCP connection.\r\nconst http = require('http');\r\n\r\nlet connections = 0;\r\nconst server = http.createServer((req, res) => res.end('ok ' + req.url));\r\nserver.on('connection', () => connections++);\r\n\r\nserver.listen(0, '127.0.0.1', () => {\r\n const agent = new http.Agent({ keepAlive: true });\r\n const get = (path, then) =>\r\n http.get({ host: '127.0.0.1', port: server.address().port, path, agent }, (res) => {\r\n res.resume();\r\n res.on('end', () => {\r\n console.log(path + ': reused socket = ' + res.req.reusedSocket);\r\n setImmediate(then); // let the agent put the socket back in its pool first\r\n });\r\n });\r\n get('/one', () =>\r\n get('/two', () => {\r\n console.log('connections opened: ' + connections);\r\n agent.destroy();\r\n server.close();\r\n }));\r\n});\r\n","racy":false,"output":["/one: reused socket = false","/two: reused socket = true","connections opened: 1"],"recording":"rec/http-keep-alive.nmrec.gz","steps":[{"index":124,"title":"The first request opens a connection","text":"The first request had to open a TCP connection: one \"TCP connect\" request appeared under Pending I/O before it."},{"index":215,"title":"The second reuses it","text":"The second request went over the same connection: no new connect request, no new server connection."}]}},"prev":{"id":"http-two-requests","title":"Two overlapping requests"},"next":{"id":"slow-handler","title":"A slow handler blocks everyone, and the fix"}}
@@ -0,0 +1 @@
1
+ {"id":"loop-phases","chapter":"event-loop","title":"The phases of the event loop, one by one","summary":"Each turn of the event loop visits its phases in a fixed order. One tiny program per phase, and exactly where Windows differs from Linux and macOS.","blocks":[{"t":"p","text":["By the end of this lesson you can name the phases of one turn of the event loop in order, say which kind of callback runs in which phase, and say where Windows and Linux differ."]},{"t":"h","level":2,"id":"the-order","text":"The order"},{"t":"p","text":["The event loop is a function in libuv called ",{"t":"code","text":"uv_run"},". In Node 26.13.1 it works the same way on Windows, Linux and macOS. Before its first turn, it runs the timers that are already due, once. Then every turn visits these phases, in this order:"]},{"t":"list","ordered":true,"items":[["The ",{"t":"strong","text":"pending phase"},": callbacks that libuv put off from the previous turn."],["Two internal phases, idle and prepare, which Node keeps for itself."],[{"t":"strong","text":"poll"},": libuv asks the operating system what has finished, such as data that arrived on a connection, and handles it. When nothing is due, the loop waits here, without using the CPU."],["The pending phase again, up to 8 times, for callbacks that the poll phase put off."],["The ",{"t":"strong","text":"check phase"},": callbacks given to ",{"t":"code","text":"setImmediate"},"."],["The ",{"t":"strong","text":"close phase"},": callbacks for handles that were closed, such as a socket's ",{"t":"code","text":"'close'"}," event."],["The timers phase: callbacks of timers that are due."]]},{"t":"p","text":["Here is the same order as libuv's code runs it:"]},{"t":"code","lang":"text","text":"run due timers once, before the first turn\nthen, every turn:\n pending callbacks put off from the last turn\n idle, prepare internal\n poll wait for I/O, and handle it\n pending again, up to 8 times\n check setImmediate callbacks\n close close callbacks\n timers due setTimeout and setInterval callbacks"},{"t":"p","text":["To read it in Node's source code, open ",{"t":"ui","text":"Call paths"}," on the map and choose ",{"t":"path","id":"p:event-loop-turn","text":"One turn of the event loop (uv_run), on Unix and Windows"},"."]},{"t":"p","text":["nodejs-map places each turn boundary where the recording shows that a new turn has started, so turn numbers on screen are inferred."]},{"t":"h","level":2,"id":"timers","text":"Timers"},{"t":"example","example":"timers-phase"},{"t":"p","text":["Due timers run in the timers phase, in order of due time. Node reports each time it runs its timers, so this phase is observed."]},{"t":"h","level":2,"id":"poll-and-pending-i-o-results","text":"Poll and pending: I/O results"},{"t":"example","example":"phase-io"},{"t":"p","text":[{"t":"code","text":"fs.stat"}," hands its work to the thread pool. When the answer is ready, the event loop runs the callback. Here Windows and the other systems differ:"]},{"t":"list","ordered":false,"items":[["On Linux and macOS, finished thread pool work wakes up the poll phase, and the callback runs inside poll."],["On Windows, poll only collects what has finished. The callbacks run in the pending phase right after poll. The screen shows that as \"pending (after poll)\"."]]},{"t":"p","text":["The recordings of this course were made on Windows. The phase on screen is inferred from the kind of callback that ran."]},{"t":"h","level":2,"id":"check-setimmediate","text":"Check: setImmediate"},{"t":"example","example":"phase-check"},{"t":"p","text":[{"t":"code","text":"setImmediate(fn)"}," runs ",{"t":"code","text":"fn"}," in the check phase, in the order the callbacks were added. An immediate added while the check phase is running waits for the next turn. Node reports the check phase, so it is observed."]},{"t":"h","level":2,"id":"close-close-callbacks","text":"Close: close callbacks"},{"t":"example","example":"phase-close"},{"t":"p","text":["When a socket or a server has been closed, its ",{"t":"code","text":"'close'"}," event comes from the close phase near the end of the turn. nodejs-map knows a callback is a close callback because Node marks the handle when ",{"t":"code","text":"close()"}," is called. The phase is inferred."]},{"t":"note","kind":"honest","text":["On the official Node build, Node reports the timers and check phases itself; the other phases on the screen are inferred from the kind of callback that ran. Where the kind leaves the phase open, the screen leaves it open too, rather than guessing."]},{"t":"check","question":["In one turn, a timer is due, an immediate is waiting, and a socket has received data. In which order do their callbacks run?"],"answer":["The socket data first (in poll, or on Windows in the pending phase right after it), then the immediate (check), then the timer (timers, at the end of the turn)."]}],"examples":{"timers-phase":{"id":"timers-phase","title":"Timers with different delays and the timers phase","name":"timer-order.js","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,"output":["D delay 1","E delay 0 (same as 1)","B delay 100","C delay 100","A delay 200"],"recording":"rec/timers-phase.nmrec.gz","steps":[{"index":29,"title":"Five timers wait","text":"The script has set five timers. Timers lists them soonest due first: two \"setTimeout 1 ms\" chips (D, and E, which asked for 0 ms), then two \"setTimeout 100 ms\" and one \"setTimeout 200 ms\"."},{"index":38,"title":"The first timers phase","text":"The event loop reaches its timers phase and runs every timer that is due."},{"index":48,"title":"D and E in the same phase","text":"E was created after D, with the same delay, so it runs right after D, in the same timers phase."},{"index":66,"title":"About 100 ms later: B and C","text":"Nothing is due for about 100 ms, so the loop waits. Then B and C are due together, and run in the order they were created, in one timers phase."},{"index":93,"title":"A runs last","text":"A was set first but has the longest delay, so it runs last. Timers run in order of when they are due, not in the order of the setTimeout calls."}]},"phase-io":{"id":"phase-io","title":"An I/O callback: fs.stat","name":"phase-io.js","module":"commonjs","text":"// An I/O callback: fs.stat asks the thread pool, and the loop delivers the answer.\nconst fs = require('fs');\n\nfs.stat(__filename, (err, stats) => {\n console.log('stat callback: is a file = ' + stats.isFile());\n});\nconsole.log('script end');\n","racy":false,"output":["script end","stat callback: is a file = true"],"recording":"rec/phase-io.nmrec.gz","steps":[{"index":17,"title":"A request for the pool","text":"fs.stat created a request, the \"fs.stat\" chip, and handed it to the thread pool."},{"index":32,"title":"The answer is delivered","text":"On Windows, where this was recorded, libuv runs the callbacks of finished requests in the pending phase right after poll; on Linux and macOS this callback runs inside poll. Node does not report this phase, so it is marked inferred."}]},"phase-check":{"id":"phase-check","title":"setImmediate and the check phase","name":"phase-check.js","module":"commonjs","text":"// setImmediate callbacks run in the check phase, one turn of the loop after the script.\nsetImmediate(() => {\n console.log('immediate 1');\n setImmediate(() => console.log('immediate 3 (queued by immediate 1: next turn)'));\n});\nsetImmediate(() => console.log('immediate 2'));\nconsole.log('script end');\n","racy":false,"output":["script end","immediate 1","immediate 2","immediate 3 (queued by immediate 1: next turn)"],"recording":"rec/phase-check.nmrec.gz","steps":[{"index":20,"title":"Two immediates wait","text":"Two \"setImmediate\" chips wait under Immediates."},{"index":33,"title":"The check phase runs them","text":"The check phase runs the immediates in order. Node reports this phase, so it is marked observed."},{"index":59,"title":"Added during the phase: next turn","text":"Immediate 3 was added while the check phase was running. It waits for the next turn of the loop: the turn number on the Now tab goes up first."}]},"phase-close":{"id":"phase-close","title":"A close callback","name":"phase-close.js","module":"commonjs","text":"// Close callbacks: a socket's 'close' event comes from the loop's close phase.\nconst net = require('net');\n\nconst server = net.createServer((socket) => socket.end());\nserver.listen(0, '127.0.0.1', () => {\n const client = net.connect(server.address().port, '127.0.0.1');\n client.on('end', () => console.log('client: end'));\n client.on('close', () => {\n console.log('client: close');\n server.close(() => console.log('server: close'));\n });\n});\n","racy":false,"output":["client: end","client: close","server: close"],"recording":"rec/phase-close.nmrec.gz","steps":[{"index":31,"title":"Connecting","text":"net.connect asked the operating system for a connection: a \"TCP connect\" chip waits under Pending I/O."},{"index":62,"title":"The server ends the connection","text":"The client's 'end' event runs in a socket callback. On Windows, where this was recorded, the screen shows the pending phase after poll (inferred)."},{"index":92,"title":"The close phase","text":"Once the socket is closed, its 'close' event comes from the close phase near the end of the loop turn. That phase is inferred too."}]}},"prev":{"id":"order-and-esm","title":"The order: ticks, microtasks, then the loop, and the ES module twist"},"next":{"id":"timeout-vs-immediate","title":"setTimeout(0) or setImmediate?"}}
@@ -0,0 +1 @@
1
+ {"id":"many-clients","chapter":"networking","title":"Many clients on one thread","summary":"One server, three clients, one main thread. The event loop takes each ready socket in turn, and each callback runs on its own, one after another.","blocks":[{"t":"p","text":["By the end of this lesson you can explain how one Node process serves many connections without threads of its own."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"tcp-many-clients"},{"t":"p","text":["Three clients connect to one server and send their names. The server answers each, and the program prints all replies at the end."]},{"t":"h","level":2,"id":"what-you-saw","text":"What you saw"},{"t":"list","ordered":false,"items":[["Three connect requests wait under Pending I/O at the same time. The operating system works on all three."],["When the poll phase finds several sockets ready, libuv calls back for each, one after the other: the server's connection callback runs three times in the same phase."],["Data arrives on three sockets, and the three data callbacks run one after the other."],["The callbacks run strictly one after another: the main thread moves to the next connection once the current callback has returned."]]},{"t":"p","text":["This is why Node can hold thousands of idle connections cheaply: a waiting connection costs no thread, only an entry the operating system watches."]},{"t":"note","kind":"warn","text":["The flip side: one slow callback delays every other connection. See ",{"t":"link","text":"A slow handler blocks everyone","href":"learn:slow-handler"},"."]},{"t":"check","question":["Two clients send data at the same moment. Can their data callbacks run at the same time on two CPU cores?"],"answer":["No. Both callbacks run on the main thread, one after the other, usually in the same poll phase."]}],"examples":{"tcp-many-clients":{"id":"tcp-many-clients","title":"Three clients, one thread","name":"tcp-many-clients.js","module":"commonjs","text":"// One server, three clients, one thread: the loop serves whichever socket has data.\r\nconst net = require('net');\r\n\r\nconst server = net.createServer((socket) => {\r\n socket.on('data', (d) => socket.end('hi ' + d));\r\n});\r\n\r\nserver.listen(0, '127.0.0.1', () => {\r\n const replies = [];\r\n let closed = 0;\r\n for (const name of ['a', 'b', 'c']) {\r\n const client = net.connect(server.address().port, '127.0.0.1', () => client.write(name));\r\n client.on('data', (d) => replies.push(String(d)));\r\n client.on('close', () => {\r\n if (++closed < 3) return;\r\n console.log('replies: ' + replies.sort().join(', '));\r\n server.close(() => console.log('server closed'));\r\n });\r\n }\r\n console.log('three clients started');\r\n});\r\n","racy":false,"output":["three clients started","replies: hi a, hi b, hi c","server closed"],"recording":"rec/tcp-many-clients.nmrec.gz","steps":[{"index":61,"title":"Three connections being opened","text":"Three \"TCP connect\" chips wait under Pending I/O."},{"index":89,"title":"Accepted one after another","text":"The server's connection callback runs three times in the same phase of the loop, one connection after the other."},{"index":248,"title":"All replies are in","text":"Every client got its reply. At no moment did two socket callbacks run at once: there is one main thread, and the Stack tab never shows more than one socket callback."}]}},"prev":{"id":"tcp-step-by-step","title":"A TCP server and client, step by step"},"next":{"id":"http-one-request","title":"An HTTP server and one request"}}
@@ -0,0 +1 @@
1
+ {"id":"microtasks-belong-to-v8","chapter":"under-the-hood","title":"The microtask queue belongs to V8","summary":"The nextTick queue is Node's, written in JavaScript; the microtask queue is V8's. Node decides when V8 empties it.","blocks":[{"t":"p","text":["By the end of this lesson you can say who owns each of the two queues that run after every callback, and where in Node's source they are emptied."]},{"t":"h","level":2,"id":"the-run","text":"The run"},{"t":"example","example":"tick-before-promise"},{"t":"p","text":["Open ",{"t":"ui","text":"Call paths"}," and look at two paths: ",{"t":"path","id":"p:next-tick","text":"process.nextTick(callback): run as soon as the current JavaScript stack unwinds"}," and ",{"t":"path","id":"p:promise-then","text":"promise.then(callback): a reaction job on V8's microtask queue"},"."]},{"t":"h","level":2,"id":"two-queues-two-owners","text":"Two queues, two owners"},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"The nextTick queue"}," is a JavaScript array in Node's ",{"t":"code","text":"lib/internal/process/task_queues.js"},". ",{"t":"code","text":"process.nextTick"}," pushes onto it; ",{"t":"code","text":"processTicksAndRejections"}," runs it."],[{"t":"strong","text":"The microtask queue"}," lives inside V8. ",{"t":"code","text":"promise.then"}," on a settled promise, and ",{"t":"code","text":"queueMicrotask"},", append a job to it through V8's ",{"t":"code","text":"EnqueueMicrotask"},". V8 runs it in ",{"t":"code","text":"MicrotaskQueue::RunMicrotasks"},", taking jobs one at a time, including jobs added while it runs."]]},{"t":"h","level":2,"id":"who-decides-when","text":"Who decides when"},{"t":"p","text":["When a callback that Node called returns, ",{"t":"code","text":"InternalCallbackScope::Close"}," in Node's C++ runs:"]},{"t":"list","ordered":false,"items":[["if a nextTick is waiting, ",{"t":"code","text":"processTicksAndRejections"},", which empties the tick queue, then asks V8 to run its microtasks, and repeats until both are empty;"],["if not, it asks V8 directly for a microtask checkpoint."]]},{"t":"p","text":["So V8 owns the microtask queue, but Node chooses the moments it is emptied, and always empties its own nextTick queue first."]},{"t":"note","kind":"honest","text":["nodejs-map sees promise reactions through async_hooks (a promise is created, settles, its reaction callback starts) and places them in the microtask queue by rule, since V8 keeps its own queue private. queueMicrotask callbacks are seen the same way."]},{"t":"check","question":["In a plain CommonJS script, why does a nextTick callback run before a promise reaction that was queued earlier?"],"answer":["Because after the script Node runs processTicksAndRejections, which empties its own nextTick queue first and only then asks V8 to run the microtask queue."]}],"examples":{"tick-before-promise":{"id":"tick-before-promise","title":"nextTick runs before promise callbacks (CommonJS)","name":"tick-vs-promise.js","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,"output":["1 sync start","2 sync end","3 nextTick","4 promise then","5 queueMicrotask","6 timeout 0"],"recording":"rec/tick-before-promise.nmrec.gz","steps":[{"index":32,"title":"Everything is queued","text":"Open Queues. The nextTick queue holds two \"nextTick\" chips, the microtask queue a \"promise reaction\" and a \"queueMicrotask\" chip, and Timers a \"setTimeout 1 ms\" chip (a 0 ms timer is stored as 1 ms). None of it has run yet. The first \"nextTick\" chip is not the program's: Node added it itself while console.log wrote the first line, and it prints nothing."},{"index":38,"title":"The nextTick queue goes first","text":"The script is done, and Node empties the nextTick queue before anything else. The Stack tab says this callback came from the nextTick queue. That is marked inferred: nodejs-map worked it out from the kind of callback (Node calls it TickObject)."},{"index":47,"title":"Then the microtask queue","text":"Only when the nextTick queue is empty does V8 run the microtask queue. The promise callback goes first, because it was added first. The queueMicrotask callback waits behind it in the same queue."},{"index":65,"title":"The timer comes last","text":"The 0 ms timer runs only after both queues are empty, when the event loop reaches its timers phase. Node reported this phase itself, so it is marked observed."}]}},"prev":{"id":"one-libuv-timer","title":"How all your timers sit on one libuv timer"},"next":{"id":"stepping-into-node","title":"Debugging Node's own JavaScript"}}
@@ -0,0 +1 @@
1
+ {"id":"next-tick","chapter":"event-loop","title":"process.nextTick","summary":"A process.nextTick callback runs as soon as the current JavaScript has finished, before promise callbacks, timers and I/O. Its queue is emptied completely each time.","blocks":[{"t":"p","text":["By the end of this lesson you can say when Node runs the callbacks of its fastest queue, and why a callback added to that queue while it is being emptied still runs before anything else."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"p","text":["Node has a queue of its own for callbacks that should run right after the code that is running now: the ",{"t":"strong","text":"nextTick queue"},". You add a callback to it with ",{"t":"code","text":"process.nextTick(fn)"},"."]},{"t":"example","example":"next-tick"},{"t":"p","text":["The program sets a 0 ms timer, then calls ",{"t":"code","text":"process.nextTick"}," with a callback that calls ",{"t":"code","text":"process.nextTick"}," again. Run it, and step through it with ",{"t":"ui","text":"Queues"}," open."]},{"t":"h","level":2,"id":"what-you-see","text":"What you see"},{"t":"list","ordered":true,"items":[["The script prints \"1. script end\". Two things wait: the timer under Timers, and a callback under nextTick queue."],["The script has ended, and the nextTick callback runs at once, before the timer. It schedules another nextTick callback."],["That second callback also runs at once, before the timer."],["Only then does the event loop go on, and the timer runs."]]},{"t":"h","level":2,"id":"what-process-nexttick-does","text":"What process.nextTick does"},{"t":"p","text":[{"t":"code","text":"process.nextTick(fn)"}," puts ",{"t":"code","text":"fn"}," in the nextTick queue, which belongs to Node itself. Despite its name, the callback runs at the end of the current JavaScript, well before the next turn of the loop. One callback in this queue is often called a tick."]},{"t":"p","text":["When the current JavaScript has finished, whether it is the script or a callback, Node empties the nextTick queue before it does anything else."]},{"t":"p","text":["\"Empties\" means completely. A tick that is added while the queue is being emptied runs in the same round. Only when the queue is empty does Node move on."]},{"t":"h","level":2,"id":"ticks-and-promises-together","text":"Ticks and promises together"},{"t":"example","example":"nested-ticks-and-microtasks"},{"t":"p","text":["This program mixes ticks and promise callbacks, which add more of each other. Follow ",{"t":"ui","text":"Queues"}," step by step."]},{"t":"p","text":["Each queue is emptied completely, including what is added to it while it runs, before Node moves to the other queue. The next lesson is about the promise side."]},{"t":"note","kind":"warn","text":["A tick that always adds another tick keeps Node in that queue for good, with promise callbacks, timers and I/O all waiting. Use ",{"t":"code","text":"process.nextTick"}," for \"right after this code\", and ",{"t":"code","text":"setImmediate"}," or a timer for anything that repeats."]},{"t":"check","question":[{"t":"code","text":"setTimeout(() => console.log('t'), 0); process.nextTick(() => console.log('n')); console.log('s');"}," What is printed?"],"answer":["s, n, t. The script runs to its end, then the nextTick queue is emptied, then the event loop runs the timer."]}],"examples":{"next-tick":{"id":"next-tick","title":"process.nextTick before the timer","name":"next-tick.js","module":"commonjs","text":"// process.nextTick runs right after the current JavaScript finishes, before timers and I/O.\nsetTimeout(() => console.log('4. setTimeout 0'), 0);\n\nprocess.nextTick(() => {\n console.log('2. nextTick');\n process.nextTick(() => console.log('3. nextTick queued by a nextTick'));\n});\n\nconsole.log('1. script end');\n","racy":false,"output":["1. script end","2. nextTick","3. nextTick queued by a nextTick","4. setTimeout 0"],"recording":"rec/next-tick.nmrec.gz","steps":[{"index":21,"title":"The script ends","text":"The nextTick queue holds the program's \"nextTick\" chip, and Timers holds the 0 ms timer."},{"index":27,"title":"nextTick runs first","text":"The tick runs before the timer, and adds another tick."},{"index":36,"title":"The new tick runs at once","text":"The new tick runs in the same round: Node empties the nextTick queue completely, including ticks added meanwhile, before the loop goes on."},{"index":48,"title":"Then the timer","text":"Only then does the event loop reach its timers phase and run the timer."}]},"nested-ticks-and-microtasks":{"id":"nested-ticks-and-microtasks","title":"Ticks and microtasks that queue each other","name":"microtask-nesting.js","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,"output":["sync start","sync end","tick A","tick D (queued by tick A)","promise B","promise C (queued by tick A)","microtask F (queued by promise B)","tick E (queued by promise B)"],"recording":"rec/nested-ticks-and-microtasks.nmrec.gz","steps":[{"index":34,"title":"Tick A runs and adds more","text":"Tick A is the first of the program's callbacks to run. While it runs, it adds promise C and another tick, D: watch them appear in Queues."},{"index":48,"title":"Tick D runs before any promise","text":"Tick D was added while the nextTick queue was being emptied, so it runs in the same round. It runs before promise B, which has been waiting since the script."},{"index":57,"title":"Now the microtask queue: B before C","text":"The nextTick queue is empty, so the microtasks run. Promise B was added by the script, so it is ahead of promise C. B adds tick E and microtask F."},{"index":75,"title":"F runs in the same round","text":"Microtask F was added while the microtask queue was running, so it runs in this same round, right after C. Tick E is still waiting in the nextTick queue."},{"index":82,"title":"Back to the nextTick queue for E","text":"Only when the microtask queue is empty does Node go back to the nextTick queue and run tick E."}]}},"prev":{"id":"timers-are-not-now","title":"What a delay really means"},"next":{"id":"promises-and-microtasks","title":"Promises and microtasks"}}
@@ -0,0 +1 @@
1
+ {"id":"observed-and-inferred","chapter":"under-the-hood","title":"How the tool knows what it shows","summary":"The three sources nodejs-map listens to on the official Node build, the rules that turn them into queues and phases, and the specially built Node used to check those rules.","blocks":[{"t":"p","text":["By the end of this lesson you can say where each fact on the screen comes from, and how anyone could find out that an inferred fact is wrong."]},{"t":"h","level":2,"id":"what-the-official-node-build-reports","text":"What the official Node build reports"},{"t":"example","example":"first-run"},{"t":"p","text":["When the local app runs your program, it switches on three ways in which Node reports what it does:"]},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"async_hooks"},": a module of Node, ",{"t":"code","text":"node:async_hooks"},", that calls functions of nodejs-map when Node creates something that can call back later (a timer, a request, a promise), when its callback starts and ends, and when a promise settles."],[{"t":"strong","text":"trace events"},": timed reports from Node's own C++ code, such as \"running timers now\" or \"running immediates now\", and the start and end of work on a pool thread."],[{"t":"strong","text":"the DevTools protocol"},": the same connection that Chrome DevTools uses to stop a program at a breakpoint and step through it."]]},{"t":"p","text":["Open ",{"t":"ui","text":"Events"}," on any run. Every row is one report from these sources, or a fact that nodejs-map worked out from them. It is the raw material of every other panel."]},{"t":"h","level":2,"id":"rules","text":"Rules"},{"t":"p","text":["A fact that nodejs-map works out names its rule. A rule says what was seen (\"a callback of type Timeout started\"), what is concluded (\"so the loop is in the timers phase\"), on which systems that holds, and which lines of Node's source code it relies on."]},{"t":"p","text":["Click the mark of any inferred fact to read its rule. The lines it cites open on the map."]},{"t":"h","level":2,"id":"checking-the-rules","text":"Checking the rules"},{"t":"p","text":["A rule can be wrong. To find out, nodejs-map has a patched Node, the ",{"t":"strong","text":"probe build"},", that reports the event loop directly: each phase as it begins and ends, and each pool job on its thread."]},{"t":"p","text":["The project runs the same programs on the probe build and on the official build, and compares what the rules inferred with what the probe build observed."]},{"t":"p","text":["That comparison has already caught mistakes. It showed that the close callbacks of sockets run in the close phase, and that the answers of a DNS server, asked with ",{"t":"code","text":"dns.resolve"},", arrive in the check phase. An earlier, simpler rule had placed them elsewhere. The rules were corrected. Where the kind of a callback leaves its phase open, the screen now leaves it open too."]},{"t":"note","kind":"honest","text":["The probe build runs on Linux today, and that is where the comparison runs. On Windows, the checks that work without it still run."]},{"t":"check","question":["The screen says \"pending (after poll)\", with the inferred mark. Did Node report that phase?"],"answer":["No. The inferred mark means nodejs-map concluded the phase from the kind of callback that ran, with a written rule. Click the mark to read that rule."]}],"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":"pipeline-errors","title":"pipeline and errors"},"next":{"id":"follow-readfile","title":"Following one fs.readFile through lib/, src/, libuv and back"}}
@@ -0,0 +1 @@
1
+ {"id":"one-libuv-timer","chapter":"under-the-hood","title":"How all your timers sit on one libuv timer","summary":"Node keeps your timers in JavaScript lists, one per duration, and gives libuv a single timer for the earliest of them.","blocks":[{"t":"p","text":["By the end of this lesson you can explain how a thousand ",{"t":"code","text":"setTimeout"}," calls cost libuv one timer, and what runs when that timer fires."]},{"t":"h","level":2,"id":"the-run","text":"The run"},{"t":"example","example":"timers-phase"},{"t":"p","text":["Open ",{"t":"ui","text":"Call paths"}," and choose ",{"t":"path","id":"p:set-timeout","text":"setTimeout(callback, ms): from the call to the callback"},", then step through the run."]},{"t":"h","level":2,"id":"in-javascript-lists-per-duration","text":"In JavaScript: lists per duration"},{"t":"list","ordered":false,"items":[[{"t":"code","text":"setTimeout"}," creates a ",{"t":"code","text":"Timeout"}," object (a delay under 1 ms becomes 1 ms) and appends it to a list in ",{"t":"code","text":"lib/internal/timers.js"},". There is one list per duration: all 100 ms timers share one list, in the order they were created."],["The lists are kept in a priority queue ordered by when each list's first timer is due."],["Only when a new list would be due before every other list does JavaScript ask the C++ side to move the one libuv timer."]]},{"t":"h","level":2,"id":"in-c-and-libuv-one-timer","text":"In C++ and libuv: one timer"},{"t":"list","ordered":false,"items":[[{"t":"code","text":"Environment::ScheduleTimer"}," starts a single libuv timer for the whole Node environment, with ",{"t":"code","text":"RunTimers"}," as its callback."],["Before polling, the event loop asks how long it may wait: until that timer is due. That is how a waiting process wakes up in time."],["In the timers phase, libuv sees its one timer is due and calls ",{"t":"code","text":"RunTimers"},", which calls ",{"t":"code","text":"processTimers"}," in JavaScript. It runs every due list, earliest first, running the nextTick and microtask queues between timers, and tells libuv when to fire next."]]},{"t":"p","text":["That is why the screen shows a single \"timer fired\" for a timers phase, followed by one callback per ",{"t":"code","text":"setTimeout"}," that was due."]},{"t":"note","kind":"honest","text":["Node reports each run of ",{"t":"code","text":"RunTimers"}," as a timed section, so the timers phase is observed. The JavaScript lists are Node's own, so the Timers view is rebuilt from the timers' creation and callbacks."]},{"t":"check","question":["Two timers are due in the same timers phase. A promise callback is queued by the first. Does it run before the second timer's callback?"],"answer":["Yes. Node empties the nextTick and microtask queues between timer callbacks, so the promise callback runs before the second timer."]}],"examples":{"timers-phase":{"id":"timers-phase","title":"Timers with different delays and the timers phase","name":"timer-order.js","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,"output":["D delay 1","E delay 0 (same as 1)","B delay 100","C delay 100","A delay 200"],"recording":"rec/timers-phase.nmrec.gz","steps":[{"index":29,"title":"Five timers wait","text":"The script has set five timers. Timers lists them soonest due first: two \"setTimeout 1 ms\" chips (D, and E, which asked for 0 ms), then two \"setTimeout 100 ms\" and one \"setTimeout 200 ms\"."},{"index":38,"title":"The first timers phase","text":"The event loop reaches its timers phase and runs every timer that is due."},{"index":48,"title":"D and E in the same phase","text":"E was created after D, with the same delay, so it runs right after D, in the same timers phase."},{"index":66,"title":"About 100 ms later: B and C","text":"Nothing is due for about 100 ms, so the loop waits. Then B and C are due together, and run in the order they were created, in one timers phase."},{"index":93,"title":"A runs last","text":"A was set first but has the longest delay, so it runs last. Timers run in order of when they are due, not in the order of the setTimeout calls."}]}},"prev":{"id":"follow-readfile","title":"Following one fs.readFile through lib/, src/, libuv and back"},"next":{"id":"microtasks-belong-to-v8","title":"The microtask queue belongs to V8"}}
@@ -0,0 +1 @@
1
+ {"id":"order-and-esm","chapter":"event-loop","title":"The order: ticks, microtasks, then the loop, and the ES module twist","summary":"After every callback Node empties the nextTick queue, then the microtask queue, before the event loop goes on. In an ES module the top level is itself a microtask, which swaps ticks and promises.","blocks":[{"t":"p","text":["By the end of this lesson you can predict the order of nextTick, promise and timer callbacks in a CommonJS script and in an ES module, and explain the difference."]},{"t":"h","level":2,"id":"the-rule","text":"The rule"},{"t":"p","text":["After the script, and after every callback the event loop runs, Node does this before the loop goes on:"]},{"t":"list","ordered":true,"items":[["Empty the nextTick queue."],["Empty the microtask queue."],["If either step added new ticks, start again at 1."]]},{"t":"p","text":["Everything else, such as timers, ",{"t":"code","text":"setImmediate"}," callbacks and I/O results, is run by the event loop itself. Some articles call these ",{"t":"strong","text":"macrotasks"},": each one runs, then the two queues are emptied, then the next one runs."]},{"t":"h","level":2,"id":"in-a-commonjs-script","text":"In a CommonJS script"},{"t":"example","example":"tick-before-promise"},{"t":"p","text":["First the tick, then the promise callback and the ",{"t":"code","text":"queueMicrotask"}," callback, then the timer. Exactly the rule above."]},{"t":"h","level":2,"id":"in-an-es-module","text":"In an ES module"},{"t":"example","example":"esm-twist"},{"t":"p","text":["The same calls, in an ",{"t":"code","text":".mjs"}," file, print the promise callback before the tick."]},{"t":"p","text":["Step to the first line of output and open ",{"t":"ui","text":"Stack"},". The top level of the module is running inside a \"promise reaction\": Node runs the body of an ES module as a promise callback, so the body is itself a microtask."]},{"t":"p","text":["V8 keeps running microtasks until its queue is empty. So the promise callback that the module added runs right after the module body, in the same round, before Node gets back to its nextTick queue."]},{"t":"note","kind":"tip","text":["In code that must work as CommonJS and as an ES module, chain the work explicitly wherever the order matters: ticks and promise callbacks come in a different order in the two."]},{"t":"check","question":["In an ES module: ",{"t":"code","text":"process.nextTick(() => console.log('tick')); Promise.resolve().then(() => console.log('then'));"}," Which line comes first?"],"answer":["\"then\". The module body runs as a microtask. The promise callback runs in the same round of the microtask queue, and the nextTick queue is emptied only after that."]}],"examples":{"tick-before-promise":{"id":"tick-before-promise","title":"nextTick runs before promise callbacks (CommonJS)","name":"tick-vs-promise.js","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,"output":["1 sync start","2 sync end","3 nextTick","4 promise then","5 queueMicrotask","6 timeout 0"],"recording":"rec/tick-before-promise.nmrec.gz","steps":[{"index":32,"title":"Everything is queued","text":"Open Queues. The nextTick queue holds two \"nextTick\" chips, the microtask queue a \"promise reaction\" and a \"queueMicrotask\" chip, and Timers a \"setTimeout 1 ms\" chip (a 0 ms timer is stored as 1 ms). None of it has run yet. The first \"nextTick\" chip is not the program's: Node added it itself while console.log wrote the first line, and it prints nothing."},{"index":38,"title":"The nextTick queue goes first","text":"The script is done, and Node empties the nextTick queue before anything else. The Stack tab says this callback came from the nextTick queue. That is marked inferred: nodejs-map worked it out from the kind of callback (Node calls it TickObject)."},{"index":47,"title":"Then the microtask queue","text":"Only when the nextTick queue is empty does V8 run the microtask queue. The promise callback goes first, because it was added first. The queueMicrotask callback waits behind it in the same queue."},{"index":65,"title":"The timer comes last","text":"The 0 ms timer runs only after both queues are empty, when the event loop reaches its timers phase. Node reported this phase itself, so it is marked observed."}]},"esm-twist":{"id":"esm-twist","title":"The ES module twist: promises before nextTick","name":"esm-tick-vs-promise.mjs","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,"output":["1 sync start","2 sync end","3 promise then","4 nextTick"],"recording":"rec/esm-twist.nmrec.gz","steps":[{"index":59,"title":"The module body is a microtask","text":"Look at the Stack tab while the module prints its first line. The top-level code is running inside a \"promise reaction\" callback (type PROMISE), not as a plain script."},{"index":70,"title":"Both are queued","text":"The module has added a tick and a promise callback. Queues shows two \"nextTick\" chips (the first is Node's own, from console.log) and one \"promise reaction\"."},{"index":78,"title":"The promise callback runs first","text":"The module body was itself a microtask, and V8 keeps running microtasks until its queue is empty. So the promise callback runs while the tick still waits."},{"index":105,"title":"Then the tick","text":"With the microtask queue empty, Node empties the nextTick queue. In the CommonJS lesson these two lines came out the other way round. The module made many more promises than Queues ever listed: a promise callback is listed only from the moment its promise has settled until it runs, and every one listed here ran."}]}},"prev":{"id":"async-await","title":"async/await is promises"},"next":{"id":"loop-phases","title":"The phases of the event loop, one by one"}}
@@ -0,0 +1 @@
1
+ {"id":"pipeline-errors","chapter":"streams","title":"pipeline and errors","summary":"pipeline reports the first error of any stream once, destroys every stream, and calls back. With files, the callback comes after the last file is closed.","blocks":[{"t":"p","text":["By the end of this lesson you can handle errors in a chain of streams and know when pipeline's callback runs."]},{"t":"h","level":2,"id":"an-error-in-the-middle","text":"An error in the middle"},{"t":"example","example":"pipeline-error"},{"t":"p","text":["The transform rejects the chunk \"two\". ",{"t":"code","text":"pipeline"}," calls back once with that error and destroys all three streams, so nothing is left open."]},{"t":"p","text":[{"t":"code","text":"pipeline"}," does that clearing up for you. With ",{"t":"code","text":"a.pipe(b).pipe(c)"}," you would listen for ",{"t":"code","text":"'error'"}," on every stream and close the others yourself."]},{"t":"h","level":2,"id":"files","text":"Files"},{"t":"example","example":"stream-pipeline-file"},{"t":"p","text":["With real files the reads and writes go through the thread pool, so the chunks arrive from the event loop's I/O step. ",{"t":"code","text":"pipeline"}," calls back after the output file has been finished and closed, so the callback can safely read it."]},{"t":"check","question":["In a pipeline of a file reader, a gzip transform and a file writer, the disk fills up during the write. How many times is the pipeline callback called, and what happens to the reader?"],"answer":["Once, with the write error. pipeline destroys the reader and the gzip stream too, so no file stays open."]}],"examples":{"pipeline-error":{"id":"pipeline-error","title":"An error in the middle of a pipeline","name":"pipeline-error.js","module":"commonjs","text":"// pipeline() connects streams and reports the first error once, then destroys every stream.\nconst { Readable, Transform, Writable, pipeline } = require('stream');\n\nconst source = Readable.from(['one', 'two', 'three']);\nconst check = new Transform({\n transform(chunk, enc, cb) {\n if (String(chunk) === 'two') return cb(new Error('bad chunk \"two\"'));\n console.log('transform ' + chunk);\n cb(null, chunk);\n },\n});\nconst sink = new Writable({ write: (chunk, enc, cb) => cb() });\n\npipeline(source, check, sink, (err) => {\n console.log('pipeline callback: ' + err.message);\n console.log('source destroyed = ' + source.destroyed + ', sink destroyed = ' + sink.destroyed);\n});\n","racy":false,"output":["transform one","pipeline callback: bad chunk \"two\"","source destroyed = true, sink destroyed = true"],"recording":"rec/pipeline-error.nmrec.gz","steps":[{"index":35,"title":"The first chunk passes","text":"The first chunk goes through the transform."},{"index":99,"title":"One error, one callback","text":"The second chunk fails. pipeline destroyed every stream and called back once, with the error."}]},"stream-pipeline-file":{"id":"stream-pipeline-file","title":"A pipeline between two files","name":"stream-pipeline-file.js","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,"output":["sync: pipeline started","pipeline done: err=undefined","output: HELLO STREAMS","cleaned up: true"],"recording":"rec/stream-pipeline-file.nmrec.gz","steps":[{"index":39,"title":"Started","text":"The file streams were opened and connected; reading and writing happen later, through the thread pool."},{"index":200,"title":"Finished","text":"pipeline calls back after the output file has been written and closed."}]}},"prev":{"id":"backpressure","title":"Backpressure made visible"},"next":{"id":"observed-and-inferred","title":"How the tool knows what it shows"}}
@@ -0,0 +1 @@
1
+ {"id":"playback","chapter":"start","title":"Watching a run, step by step","summary":"Play a run fast or slowly, step through it, jump with the timeline, and know what a replay tells you.","blocks":[{"t":"p","text":["By the end of this lesson you can move to any moment of a run, and say what a replay tells you."]},{"t":"h","level":2,"id":"a-program-with-five-timers","text":"A program with five timers"},{"t":"example","example":"timers-phase"},{"t":"p","text":["The program sets five timers with different delays. Play it with ",{"t":"ui","text":"Play"},", then try each control below."]},{"t":"h","level":2,"id":"the-playback-bar","text":"The playback bar"},{"t":"image","src":"img/playback-bar.webp","alt":"The playback bar","width":1280,"height":800,"caption":"The playback bar works the same for a run you just made and for a recording you opened."},{"t":"list","ordered":false,"items":[[{"t":"ui","text":"Play"}," plays the run. Press it again to pause."],[{"t":"ui","text":"Back one step"}," and ",{"t":"ui","text":"Forward one step"}," move one step at a time."],[{"t":"ui","text":"Go to the start"}," and ",{"t":"ui","text":"Go to the end"}," jump to the first and to the last moment of the run."],[{"t":"ui","text":"Playback speed"}," sets how fast the run plays."],[{"t":"ui","text":"the timeline"}," is the whole run, from start to end. Click anywhere on it to jump there, or drag along it. Coloured marks on it show where callbacks ran and where output was printed."]]},{"t":"h","level":2,"id":"how-far-one-step-goes","text":"How far one step goes"},{"t":"p","text":[{"t":"ui","text":"What the step buttons move by"}," decides what one step is. At first, one step is one meaningful thing that happened, such as a callback starting or a line being printed."]},{"t":"p","text":["You can also make a step jump to the next callback, the next piece of output, the next phase of the event loop, or the next turn of the loop. Choose \"by callback\" and step through this program: each step lands on the start of the next callback."]},{"t":"h","level":2,"id":"quiet-stretches-are-shortened","text":"Quiet stretches are shortened"},{"t":"p","text":["Playback keeps its own pace rather than the clock's. This program waits about 100 ms with nothing to do. Played at real speed, the screen would sit still."]},{"t":"p","text":["So when nothing happens for a while, playback skips ahead, and the playback bar says how long the skipped stretch was."]},{"t":"h","level":2,"id":"what-a-replay-is","text":"What a replay is"},{"t":"p","text":["A replay shows the recording of the run, moment by moment. Your program ran once, and that run is what you are watching."]},{"t":"p","text":["Stepping back shows you the screen as it was at that earlier moment of the recording."]},{"t":"note","kind":"honest","text":["A run at full speed records each callback, each entry into a queue and each line of output, with the line of your program that caused it. To follow your own code line by line, stop it at a line, as the lesson ",{"t":"link","text":"Stopping at a line","href":"learn:breakpoints"}," shows."]},{"t":"check","question":["You go back to the start of a replay and press Play again. Is the program run a second time?"],"answer":["No. The replay shows the recorded run again; nothing is executed. Only Run, in the local app, starts the program."]}],"examples":{"timers-phase":{"id":"timers-phase","title":"Timers with different delays and the timers phase","name":"timer-order.js","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,"output":["D delay 1","E delay 0 (same as 1)","B delay 100","C delay 100","A delay 200"],"recording":"rec/timers-phase.nmrec.gz","steps":[{"index":29,"title":"Five timers wait","text":"The script has set five timers. Timers lists them soonest due first: two \"setTimeout 1 ms\" chips (D, and E, which asked for 0 ms), then two \"setTimeout 100 ms\" and one \"setTimeout 200 ms\"."},{"index":38,"title":"The first timers phase","text":"The event loop reaches its timers phase and runs every timer that is due."},{"index":48,"title":"D and E in the same phase","text":"E was created after D, with the same delay, so it runs right after D, in the same timers phase."},{"index":66,"title":"About 100 ms later: B and C","text":"Nothing is due for about 100 ms, so the loop waits. Then B and C are due together, and run in the order they were created, in one timers phase."},{"index":93,"title":"A runs last","text":"A was set first but has the longest delay, so it runs last. Timers run in order of when they are due, not in the order of the setTimeout calls."}]}},"prev":{"id":"glossary","title":"Glossary"},"next":{"id":"three-marks","title":"The three marks: observed, inferred, model"}}
@@ -0,0 +1 @@
1
+ {"id":"pool-size","chapter":"thread-pool","title":"Changing the pool size","summary":"UV_THREADPOOL_SIZE sets the number of pool threads, as long as it is set before the pool is first used.","blocks":[{"t":"p","text":["By the end of this lesson you can change the number of thread pool threads and say when that change takes effect."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"pool-with-two-threads"},{"t":"p","text":["The first line of the program sets ",{"t":"code","text":"process.env.UV_THREADPOOL_SIZE = '2'"},". Then it starts four jobs."]},{"t":"h","level":2,"id":"what-you-saw","text":"What you saw"},{"t":"list","ordered":false,"items":[["libuv creates its threads when the pool is used for the first time, and reads ",{"t":"code","text":"UV_THREADPOOL_SIZE"}," at that moment. Set it before the first use and it works, even from inside the program."],["With two threads, four jobs run in two waves of two."],["nodejs-map reads the same variable when the first job is handed over, so the size on screen is marked inferred."]]},{"t":"note","kind":"warn","text":["Setting ",{"t":"code","text":"UV_THREADPOOL_SIZE"}," after anything has used the pool (a file read, a dns.lookup, a crypto call) changes nothing: the threads already exist. Set it at the very top of the program, or in the environment before Node starts."]},{"t":"note","kind":"tip","text":["More threads are not free. Each one is a real operating system thread, and jobs that keep the CPU busy still share the same CPU cores. libuv accepts up to 1024."]},{"t":"check","question":["A program reads a config file with ",{"t":"code","text":"fs.readFile"},", and in its callback sets ",{"t":"code","text":"UV_THREADPOOL_SIZE"}," to 8. How many pool threads are there?"],"answer":["Still four. The file read used the pool first, so the threads were already created with the default size."]}],"examples":{"pool-with-two-threads":{"id":"pool-with-two-threads","title":"The thread pool with two threads","name":"threadpool-size.js","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,"output":["queued 4 jobs, pool size set to 2","wave 1 done: 1 2","wave 2 done: 3 4"],"recording":"rec/pool-with-two-threads.nmrec.gz","steps":[{"index":18,"title":"The program sets the pool size","text":"The program set UV_THREADPOOL_SIZE to 2 itself. Node does not report the size of the pool. nodejs-map read the variable when the first \"crypto.pbkdf2\" job was handed to the pool, which is when libuv creates its threads, so the size of 2 is marked inferred."},{"index":29,"title":"Two threads, both busy","text":"The Thread pool tab now shows two threads, with jobs 1 and 2 running on them."},{"index":37,"title":"Jobs 3 and 4 wait","text":"Jobs 3 and 4 are handed over while both threads are busy, so they wait."},{"index":56,"title":"A free thread takes job 3","text":"The first thread to finish its job picked up job 3 straight away."},{"index":76,"title":"Wave 1","text":"Jobs 1 and 2 are done."},{"index":107,"title":"Wave 2","text":"Jobs 3 and 4 finish about one job's time later. With four threads, all four jobs would have run at once."}]}},"prev":{"id":"four-threads-six-jobs","title":"The thread pool: four threads, six jobs"},"next":{"id":"what-uses-the-pool","title":"What uses the thread pool"}}