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.
- package/LICENSE +21 -0
- package/README.md +95 -2
- package/dist/app/assets/LearnView-Cqz9Ux8w.js +3 -0
- package/dist/app/assets/LearnView-Cqz9Ux8w.js.map +1 -0
- package/dist/app/assets/LearnView-Nrw6YQU8.css +1 -0
- package/dist/app/assets/app.worker-DZKurLgd.js +8 -0
- package/dist/app/assets/app.worker-DZKurLgd.js.map +1 -0
- package/dist/app/assets/atlas.worker-DGHewGIv.js +2 -0
- package/dist/app/assets/atlas.worker-DGHewGIv.js.map +1 -0
- package/dist/app/assets/cm-BTWjV_Gb.js +13 -0
- package/dist/app/assets/cm-BTWjV_Gb.js.map +1 -0
- package/dist/app/assets/dist-B37Ex44M.js +2 -0
- package/dist/app/assets/dist-B37Ex44M.js.map +1 -0
- package/dist/app/assets/dist-Dv4HNg5q.js +2 -0
- package/dist/app/assets/dist-Dv4HNg5q.js.map +1 -0
- package/dist/app/assets/index-BRoted4h.css +1 -0
- package/dist/app/assets/index-eLItdROg.js +18 -0
- package/dist/app/assets/index-eLItdROg.js.map +1 -0
- package/dist/app/assets/map-CISW7_cc.css +1 -0
- package/dist/app/assets/map-mCCk9DTc.js +132 -0
- package/dist/app/assets/map-mCCk9DTc.js.map +1 -0
- package/dist/app/assets/sdf-label-font-1nAa0TP8.png +0 -0
- package/dist/app/config.json +5 -0
- package/dist/app/favicon.svg +1 -0
- package/dist/app/index.html +21 -0
- package/dist/atlas/v26.13.1/build-report.json +178 -0
- package/dist/atlas/v26.13.1/chunks/lib.bootstrap.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.core.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.crypto.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.devtools.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.events.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.fs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.modules.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.net.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.net.1.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.platform.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.process.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.rest.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.streams.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.timers.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.workers.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/lib.zlib.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.callbacks.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.crypto.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.diag.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.fs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.inspector.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.loop.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.modules.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.napi.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.net.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.net.1.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.process.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.rest.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.support.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/src.zlib.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.api.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.backends.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.fs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.loop.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.net.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.rest.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/uv.threadpool.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.api.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.asmjs.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.ast.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.base.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.baseline.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.bigint.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.builtins.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.codegen.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.codegen.riscv.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.common.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler-dispatcher.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler.backend.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.compiler.turboshaft.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.d8.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.date.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.debug.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.deoptimizer.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.diagnostics.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.dumpling.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.execution.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.extensions.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.flags.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.fuzzilli.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.handles.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.heap.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.heap.cppgc.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.ic.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.init.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.inspector.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.interpreter.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.json.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.libplatform.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.libsampler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.logging.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.maglev.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.numbers.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.objects.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.parsing.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.profiler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.regexp.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.root.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.roots.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.runtime.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.sandbox.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.snapshot.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.strings.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.tasks.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.torque.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.tracing.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.trap-handler.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.utils.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.wasm.0.json +1 -0
- package/dist/atlas/v26.13.1/chunks/v8.zone.0.json +1 -0
- package/dist/atlas/v26.13.1/edges.json +1 -0
- package/dist/atlas/v26.13.1/files.json +1 -0
- package/dist/atlas/v26.13.1/index.json +1 -0
- package/dist/atlas/v26.13.1/search.json +1 -0
- package/dist/cli.js +6268 -0
- package/dist/examples.json +1 -0
- package/dist/learn/async-await.json +1 -0
- package/dist/learn/backpressure.json +1 -0
- package/dist/learn/big-picture.json +1 -0
- package/dist/learn/blocking-the-loop.json +1 -0
- package/dist/learn/breakpoints.json +1 -0
- package/dist/learn/call-stack.json +1 -0
- package/dist/learn/first-run.json +1 -0
- package/dist/learn/follow-readfile.json +1 -0
- package/dist/learn/four-threads-six-jobs.json +1 -0
- package/dist/learn/glossary.json +1 -0
- package/dist/learn/hiding-areas.json +1 -0
- package/dist/learn/http-one-request.json +1 -0
- package/dist/learn/http-two-requests.json +1 -0
- package/dist/learn/img/big-picture.webp +0 -0
- package/dist/learn/img/first-run-queues.webp +0 -0
- package/dist/learn/img/hide-restore-strip.webp +0 -0
- package/dist/learn/img/hide-view-menu.webp +0 -0
- package/dist/learn/img/map-call-path.webp +0 -0
- package/dist/learn/img/marks-in-a-run.webp +0 -0
- package/dist/learn/img/paused-at-breakpoint.webp +0 -0
- package/dist/learn/img/paused-in-node-fs.webp +0 -0
- package/dist/learn/img/playback-bar.webp +0 -0
- package/dist/learn/img/save-and-share.webp +0 -0
- package/dist/learn/img/tour-areas.webp +0 -0
- package/dist/learn/index.json +390 -0
- package/dist/learn/keep-alive.json +1 -0
- package/dist/learn/loop-phases.json +1 -0
- package/dist/learn/many-clients.json +1 -0
- package/dist/learn/microtasks-belong-to-v8.json +1 -0
- package/dist/learn/next-tick.json +1 -0
- package/dist/learn/observed-and-inferred.json +1 -0
- package/dist/learn/one-libuv-timer.json +1 -0
- package/dist/learn/order-and-esm.json +1 -0
- package/dist/learn/pipeline-errors.json +1 -0
- package/dist/learn/playback.json +1 -0
- package/dist/learn/pool-size.json +1 -0
- package/dist/learn/prerequisites.json +1 -0
- package/dist/learn/probe-build.json +1 -0
- package/dist/learn/promises-and-microtasks.json +1 -0
- package/dist/learn/reading-a-file.json +1 -0
- package/dist/learn/rec/async-await-chain.nmrec.gz +0 -0
- package/dist/learn/rec/backpressure.nmrec.gz +0 -0
- package/dist/learn/rec/beforeexit-and-exit.nmrec.gz +0 -0
- package/dist/learn/rec/block-loop.nmrec.gz +0 -0
- package/dist/learn/rec/dns-lookup-thread-pool.nmrec.gz +0 -0
- package/dist/learn/rec/esm-twist.nmrec.gz +0 -0
- package/dist/learn/rec/eventemitter-is-synchronous.nmrec.gz +0 -0
- package/dist/learn/rec/first-run.nmrec.gz +0 -0
- package/dist/learn/rec/fs-promises-await.nmrec.gz +0 -0
- package/dist/learn/rec/fs-sync-vs-async.nmrec.gz +0 -0
- package/dist/learn/rec/http-blocking-fixed.nmrec.gz +0 -0
- package/dist/learn/rec/http-blocking.nmrec.gz +0 -0
- package/dist/learn/rec/http-keep-alive.nmrec.gz +0 -0
- package/dist/learn/rec/http-roundtrip.nmrec.gz +0 -0
- package/dist/learn/rec/http-two-requests.nmrec.gz +0 -0
- package/dist/learn/rec/interval-and-clear.nmrec.gz +0 -0
- package/dist/learn/rec/nested-ticks-and-microtasks.nmrec.gz +0 -0
- package/dist/learn/rec/next-tick.nmrec.gz +0 -0
- package/dist/learn/rec/pbkdf2-six-jobs-four-threads.nmrec.gz +0 -0
- package/dist/learn/rec/phase-check.nmrec.gz +0 -0
- package/dist/learn/rec/phase-close.nmrec.gz +0 -0
- package/dist/learn/rec/phase-io.nmrec.gz +0 -0
- package/dist/learn/rec/pipeline-error.nmrec.gz +0 -0
- package/dist/learn/rec/pool-users.nmrec.gz +0 -0
- package/dist/learn/rec/pool-with-two-threads.nmrec.gz +0 -0
- package/dist/learn/rec/promise-microtasks.nmrec.gz +0 -0
- package/dist/learn/rec/readfile-thread-pool.nmrec.gz +0 -0
- package/dist/learn/rec/run-to-completion.nmrec.gz +0 -0
- package/dist/learn/rec/split-work.nmrec.gz +0 -0
- package/dist/learn/rec/stream-pipeline-file.nmrec.gz +0 -0
- package/dist/learn/rec/streams-memory.nmrec.gz +0 -0
- package/dist/learn/rec/tcp-many-clients.nmrec.gz +0 -0
- package/dist/learn/rec/tcp-round-trip.nmrec.gz +0 -0
- package/dist/learn/rec/tick-before-promise.nmrec.gz +0 -0
- package/dist/learn/rec/timeout-vs-immediate-io.nmrec.gz +0 -0
- package/dist/learn/rec/timeout-vs-immediate-main.nmrec.gz +0 -0
- package/dist/learn/rec/timer-lateness.nmrec.gz +0 -0
- package/dist/learn/rec/timer-vs-file-read.nmrec.gz +0 -0
- package/dist/learn/rec/timers-phase.nmrec.gz +0 -0
- package/dist/learn/rec/unref-timer.nmrec.gz +0 -0
- package/dist/learn/save-and-share.json +1 -0
- package/dist/learn/slow-handler.json +1 -0
- package/dist/learn/splitting-work.json +1 -0
- package/dist/learn/staying-alive.json +1 -0
- package/dist/learn/stepping-into-node.json +1 -0
- package/dist/learn/streams-basics.json +1 -0
- package/dist/learn/tcp-step-by-step.json +1 -0
- package/dist/learn/the-map.json +1 -0
- package/dist/learn/three-marks.json +1 -0
- package/dist/learn/timeout-vs-immediate.json +1 -0
- package/dist/learn/timers-are-not-now.json +1 -0
- package/dist/learn/tour.json +1 -0
- package/dist/learn/what-it-is.json +1 -0
- package/dist/learn/what-uses-the-pool.json +1 -0
- package/dist/lessons/async-await-chain.nmrec.gz +0 -0
- package/dist/lessons/beforeexit-and-exit.nmrec.gz +0 -0
- package/dist/lessons/dns-lookup-thread-pool.nmrec.gz +0 -0
- package/dist/lessons/esm-twist.nmrec.gz +0 -0
- package/dist/lessons/eventemitter-is-synchronous.nmrec.gz +0 -0
- package/dist/lessons/fs-promises-await.nmrec.gz +0 -0
- package/dist/lessons/fs-sync-vs-async.nmrec.gz +0 -0
- package/dist/lessons/index.json +621 -0
- package/dist/lessons/interval-and-clear.nmrec.gz +0 -0
- package/dist/lessons/nested-ticks-and-microtasks.nmrec.gz +0 -0
- package/dist/lessons/pbkdf2-six-jobs-four-threads.nmrec.gz +0 -0
- package/dist/lessons/pool-with-two-threads.nmrec.gz +0 -0
- package/dist/lessons/readfile-thread-pool.nmrec.gz +0 -0
- package/dist/lessons/tcp-round-trip.nmrec.gz +0 -0
- package/dist/lessons/tick-before-promise.nmrec.gz +0 -0
- package/dist/lessons/timeout-vs-immediate-io.nmrec.gz +0 -0
- package/dist/lessons/timeout-vs-immediate-main.nmrec.gz +0 -0
- package/dist/lessons/timer-vs-file-read.nmrec.gz +0 -0
- package/dist/lessons/timers-phase.nmrec.gz +0 -0
- package/dist/preload.cjs +507 -0
- package/package.json +25 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"prerequisites","chapter":"before","title":"What you need to know, and what you need installed","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.","blocks":[{"t":"p","text":["By the end of this lesson you know whether this course is for you, what to install, and how to start nodejs-map."]},{"t":"h","level":2,"id":"what-you-should-already-know","text":"What you should already know"},{"t":"p","text":["This course is for JavaScript developers who have written Node.js programs. It builds on the things below and starts from there. If one of them is new to you, learn it first, then come back."]},{"t":"p","text":["JavaScript:"]},{"t":"list","ordered":false,"items":[["functions, arrow functions and callbacks (a callback is a function you pass to other code, to be called later);"],["closures, objects and classes;"],["errors: ",{"t":"code","text":"throw"},", ",{"t":"code","text":"try"}," and ",{"t":"code","text":"catch"},", and Node's error-first callbacks, ",{"t":"code","text":"(err, result) => ..."},";"],["promises: ",{"t":"code","text":"new Promise"},", ",{"t":"code","text":".then"},", ",{"t":"code","text":".catch"}," and ",{"t":"code","text":"Promise.resolve"},";"],[{"t":"code","text":"async"}," functions and ",{"t":"code","text":"await"},"."]]},{"t":"p","text":["Node.js:"]},{"t":"list","ordered":false,"items":[["running a file with ",{"t":"code","text":"node app.js"},";"],["loading modules with ",{"t":"code","text":"require"}," and with ",{"t":"code","text":"import"},", and installing packages with ",{"t":"code","text":"npm"},";"],["the ",{"t":"code","text":"fs"}," module: reading and writing files, with callbacks and with ",{"t":"code","text":"fs.promises"},";"],["the ",{"t":"code","text":"http"}," module: a small server with ",{"t":"code","text":"http.createServer"},", and fetching a page with ",{"t":"code","text":"http.get"},";"],["the ",{"t":"code","text":"net"}," module: a TCP server and a client, and sockets that emit ",{"t":"code","text":"'data'"},", ",{"t":"code","text":"'end'"}," and ",{"t":"code","text":"'close'"},";"],[{"t":"code","text":"EventEmitter"},": ",{"t":"code","text":"on"},", ",{"t":"code","text":"once"}," and ",{"t":"code","text":"emit"},";"],[{"t":"code","text":"setTimeout"},", ",{"t":"code","text":"setInterval"},", ",{"t":"code","text":"clearTimeout"}," and ",{"t":"code","text":"clearInterval"},"."]]},{"t":"p","text":[{"t":"code","text":"setImmediate"},", ",{"t":"code","text":"queueMicrotask"}," and Node's other ways to schedule a callback are introduced here, so you can meet them for the first time in this course."]},{"t":"h","level":2,"id":"what-the-course-teaches-you","text":"What the course teaches you"},{"t":"p","text":["Everything about how Node works inside starts from zero here. That is what this course is for."]},{"t":"p","text":["Every word about Node's insides, or about this tool, is explained the first time it is used, in a sentence or two. The last lesson of this first part, the ",{"t":"link","text":"Glossary","href":"learn:glossary"},", lists all of these words, each with a link to the lesson that explains it."]},{"t":"h","level":2,"id":"without-installing-anything","text":"Without installing anything"},{"t":"p","text":["You can read this whole course, and replay every example in it, without installing anything. The examples come with recordings, and replaying a recording needs no Node.js."]},{"t":"p","text":["To run programs yourself, and to stop them at a line, you need the local app."]},{"t":"h","level":2,"id":"what-you-need-installed","text":"What you need installed"},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"Node.js 26."}," nodejs-map runs your programs with the Node.js you have installed. Its map is built from the source code of Node 26.13.1. With that exact version, every box on the map matches the code that runs. With another version of Node 26, nodejs-map says so in the terminal and uses the map of 26.13.1."],[{"t":"strong","text":"A desktop browser"},", such as a recent Chrome or Edge. The player website opens on a phone too; the course is written for the roomier screen of a computer."]]},{"t":"h","level":2,"id":"starting-the-local-app","text":"Starting the local app"},{"t":"p","text":["Open a terminal in the folder that holds the program you want to look at, and run:"]},{"t":"code","lang":"sh","text":"npx nodejs-map app.js"},{"t":"p","text":[{"t":"code","text":"npx"}," downloads nodejs-map the first time, then starts it. nodejs-map starts a small web server on your computer, at an address on 127.0.0.1 that only your computer can reach, and opens it in your browser. The file you named is in the editor. The file name is optional."]},{"t":"p","text":["Two things keep this safe:"]},{"t":"list","ordered":false,"items":[["nodejs-map reads and runs files inside the folder you started it in, and nowhere else."],["Nothing runs until you press Run in the app."]]},{"t":"p","text":["To stop nodejs-map, press ",{"t":"kbd","text":"Ctrl+C"}," in the terminal."]},{"t":"check","question":["You have used ",{"t":"code","text":"setTimeout"}," many times, but never ",{"t":"code","text":"setImmediate"},", and you have no idea what happens inside Node when a timer fires. Is this course for you?"],"answer":["Yes. The course expects you to have used ",{"t":"code","text":"setTimeout"},", not to know how it works inside. It introduces ",{"t":"code","text":"setImmediate"},", and everything inside Node, as it goes."]}],"examples":{},"prev":{"id":"what-it-is","title":"What nodejs-map is"},"next":{"id":"tour","title":"A tour of the screen"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"probe-build","chapter":"under-the-hood","title":"The probe build: stopping between phases","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.","blocks":[{"t":"p","text":["By the end of this lesson you can say what the probe build adds to an official Node build, and what keeps running while it holds the loop."]},{"t":"h","level":2,"id":"why-a-patched-node","text":"Why a patched Node"},{"t":"p","text":["The debugger stops JavaScript, and the loop's phases are C code inside libuv, so stopping between two phases asks for a little more. The probe build is Node 26.13.1 with a few small patches that report the loop from inside libuv and add ",{"t":"strong","text":"gates"},": places where the loop waits for a click."]},{"t":"h","level":2,"id":"what-it-adds","text":"What it adds"},{"t":"list","ordered":false,"items":[["Every phase is observed, not inferred: the phase marks on screen become solid."],["Thread pool jobs are reported as they happen, not late."],["Gates: start a run stopped before its first phase, step one phase at a time, stop before Node's timers run, stop a pool job before it starts or before its result is posted."],["A frozen clock: while JavaScript is paused at a breakpoint, the loop's clock stands still, so timers do not become overdue during the pause."]]},{"t":"h","level":2,"id":"what-keeps-running-at-a-gate","text":"What keeps running at a gate"},{"t":"list","ordered":false,"items":[["Work already running on a pool thread finishes in real time."],[{"t":"code","text":"Date.now()"}," keeps going, and so do the operating system and anything on the network."]]},{"t":"note","kind":"honest","text":["Linux has a probe build today. The patches for Windows and macOS are written and waiting to be compiled, and binaries are still to be published. Until then, the controls that need the probe build say so."]},{"t":"check","question":["You hold the probe build at a gate for five seconds while a 1 s timer is waiting. When you continue, does the timer fire at once?"],"answer":["No. The loop's clock stood still at the gate, so by the loop's clock the timer still has the rest of its second to wait. ",{"t":"code","text":"Date.now()"}," inside its callback will show that the real wait was longer."]}],"examples":{},"prev":{"id":"stepping-into-node","title":"Debugging Node's own JavaScript"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"promises-and-microtasks","chapter":"event-loop","title":"Promises and microtasks","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.","blocks":[{"t":"p","text":["By the end of this lesson you can explain when a ",{"t":"code","text":".then"}," callback runs, why a chain of ",{"t":"code","text":".then"}," calls runs in several steps, and why all of them run before a 0 ms timer."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"promise-microtasks"},{"t":"p","text":["A 0 ms timer, a promise chain with two ",{"t":"code","text":".then"}," callbacks, and one ",{"t":"code","text":"queueMicrotask"}," callback. Run it with ",{"t":"ui","text":"Queues"}," open."]},{"t":"h","level":2,"id":"what-you-see","text":"What you see"},{"t":"list","ordered":false,"items":[["When the script ends, the Microtask queue holds two callbacks: the first ",{"t":"code","text":".then"},", and the ",{"t":"code","text":"queueMicrotask"}," callback. The second ",{"t":"code","text":".then"}," is not there yet."],["The first ",{"t":"code","text":".then"}," runs. When it returns \"b\", the promise of the second ",{"t":"code","text":".then"}," settles, and that callback joins the end of the queue, behind ",{"t":"code","text":"queueMicrotask"},"."],["So \"then b\" runs after the ",{"t":"code","text":"queueMicrotask"}," callback."],["The timer runs only when the Microtask queue is empty."]]},{"t":"h","level":2,"id":"what-a-microtask-is","text":"What a microtask is"},{"t":"p","text":["A microtask, you saw in the big picture, is a small task that runs as soon as the JavaScript that is running now has finished. Promise callbacks are microtasks, and so are the callbacks you give to ",{"t":"code","text":"queueMicrotask"},". They wait in the microtask queue."]},{"t":"p","text":["That queue does not belong to Node. It belongs to V8, the JavaScript engine, because promises are part of the JavaScript language."]},{"t":"p","text":["Four rules explain everything you saw:"]},{"t":"list","ordered":true,"items":[["A ",{"t":"code","text":".then"}," callback joins the queue only when its promise has settled, that is, resolved or rejected. That is why the second ",{"t":"code","text":".then"}," was not listed at first."],["The queue is first in, first out."],["A microtask added while the queue is being emptied runs in the same round."],["The event loop goes on only when the queue is empty."]]},{"t":"note","kind":"honest","text":["nodejs-map lists a promise callback from the moment its promise settles, which Node does report. V8 keeps the queue itself, so that listing is inferred."]},{"t":"check","question":["A promise chain has ten ",{"t":"code","text":".then"}," callbacks, and a ",{"t":"code","text":"setTimeout(fn, 0)"}," was set before it. Does the timer run somewhere in the middle of the chain?"],"answer":["No. Each ",{"t":"code","text":".then"}," adds the next one to the microtask queue while the queue is still being emptied. All ten run in the same round, and the timer waits until the queue is empty."]}],"examples":{"promise-microtasks":{"id":"promise-microtasks","title":"Promise callbacks are microtasks","name":"promise-microtasks.js","module":"commonjs","text":"// Promise callbacks are microtasks: they all run before the event loop moves on.\nsetTimeout(() => console.log('5. timeout'), 0);\n\nPromise.resolve('a')\n .then((v) => {\n console.log('2. then ' + v);\n return 'b';\n })\n .then((v) => console.log('4. then ' + v));\n\nqueueMicrotask(() => console.log('3. queueMicrotask'));\nconsole.log('1. script end');\n","racy":false,"output":["1. script end","2. then a","3. queueMicrotask","4. then b","5. timeout"],"recording":"rec/promise-microtasks.nmrec.gz","steps":[{"index":26,"title":"Two microtasks wait","text":"The microtask queue holds the first .then (a \"promise reaction\") and the \"queueMicrotask\" callback. The second .then is not listed yet: the promise it waits for has not settled."},{"index":34,"title":"The first .then runs","text":"When it returns \"b\", the next promise settles, and its callback joins the end of the queue, behind the queueMicrotask callback."},{"index":48,"title":"First in, first out","text":"So \"then b\" runs after queueMicrotask, in the same round of the microtask queue."},{"index":59,"title":"The timer comes after all of them","text":"The timer runs only when the microtask queue is empty."}]}},"prev":{"id":"next-tick","title":"process.nextTick"},"next":{"id":"async-await","title":"async/await is promises"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"reading-a-file","chapter":"thread-pool","title":"Reading a file: one trip through the thread pool","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.","blocks":[{"t":"p","text":["By the end of this lesson you can describe the path of ",{"t":"code","text":"fs.readFile"}," from your call to your callback, and say what ",{"t":"code","text":"readFileSync"}," does differently."]},{"t":"h","level":2,"id":"a-new-tab","text":"A new tab"},{"t":"p","text":[{"t":"ui","text":"Thread pool"}," shows the thread pool: one lane per pool thread, with the work each thread does, and the work that is waiting for a thread or for its result to be delivered."]},{"t":"p","text":["A piece of work handed to the thread pool is called a ",{"t":"strong","text":"job"},". The tab shows each job with the request that it belongs to."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"readfile-thread-pool"},{"t":"p","text":["Step through it with ",{"t":"ui","text":"Thread pool"}," open."]},{"t":"h","level":2,"id":"what-you-see","text":"What you see"},{"t":"list","ordered":false,"items":[[{"t":"code","text":"fs.readFile"}," creates a request, and hands one job to the thread pool. Then it returns at once, and the script goes on."],["A pool thread takes the job. It opens the file, reads it and closes it. In Node 26, a small file is read in one job; only a large file is read in several."],["The finished job waits under \"Finished, not delivered\" until the main thread is free and the event loop picks it up. Then your callback runs, on the main thread."]]},{"t":"p","text":["To see the code behind each stop, open ",{"t":"ui","text":"Call paths"}," and choose ",{"t":"path","id":"p:fs-readFile","text":"fs.readFile(path, callback): to the thread pool and back"},"."]},{"t":"h","level":2,"id":"sync-and-async","text":"Sync and async"},{"t":"example","example":"fs-sync-vs-async"},{"t":"p","text":[{"t":"code","text":"readFileSync"}," does the same open, read and close, but on the main thread. Nothing else can run until it returns."]},{"t":"p","text":[{"t":"code","text":"fs.stat"}," with a callback goes to the thread pool and returns at once, so the next line of the script runs before the result exists."]},{"t":"note","kind":"honest","text":["The times of pool threads arrive late on the official Node build, in batches. nodejs-map puts them back in time order, and where they sit against what the main thread did is approximate. Node reports pool threads for crypto, zlib and the one-job ",{"t":"code","text":"fs.readFile"},"; other requests, such as ",{"t":"code","text":"fs.stat"},", appear under \"Requests with the pool\", without a thread."]},{"t":"check","question":["You call ",{"t":"code","text":"fs.readFile"},", then run a loop that takes 50 ms. The file is read in 2 ms. When does your callback run?"],"answer":["After the loop has finished. A pool thread reads the file in 2 ms, but delivering the result needs the main thread, which is busy until the loop ends."]}],"examples":{"readfile-thread-pool":{"id":"readfile-thread-pool","title":"Reading a file: one trip through the thread pool","name":"readfile-callback.js","module":"commonjs","text":"// Shows: the callback path of fs.readFile. Deterministic.\n// Why: readFile returns at once. In Node 26 a small file is read as ONE\n// thread pool job: a pool thread opens, stats, reads and closes the file,\n// then hands the result back to the event loop. So the rest of the script\n// runs first, then the nextTick, and the readFile callback comes later,\n// when the loop picks the finished job up. (Its order relative to\n// setImmediate is NOT guaranteed: see readfile-vs-immediate.js.)\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\n\nconst dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-map-corpus-'));\nconst file = path.join(dir, 'data.txt');\nfs.writeFileSync(file, 'hello world');\n\nfs.readFile(file, 'utf8', (err, text) => {\n console.log('readFile callback: err=' + err + ' text=' + text);\n fs.rmSync(dir, { recursive: true, force: true });\n});\nprocess.nextTick(() => console.log('nextTick'));\nconsole.log('sync: after calling readFile');\n","racy":false,"output":["sync: after calling readFile","nextTick","readFile callback: err=null text=hello world"],"recording":"rec/readfile-thread-pool.nmrec.gz","steps":[{"index":25,"title":"One job for the pool","text":"fs.readFile created a request, the \"fs.readFile\" chip, and handed one job to the thread pool. Open the Thread pool tab."},{"index":30,"title":"A pool thread starts it","text":"A pool thread reported starting an \"fs.readfile\" job (observed). That it is this job is inferred. Reports from pool threads reach nodejs-map late, so where they sit against the main thread is approximate."},{"index":34,"title":"The thread is done","text":"The pool thread has finished. Open, read and close all happened there, in one job. The result now waits under \"Finished, not delivered\" until the main thread is free and the loop picks it up."},{"index":54,"title":"The callback runs","text":"The loop delivers the result, and the callback runs on the main thread. The script's last line and the tick came earlier, as always. On Windows this happens in the pending phase right after poll; Node did not report the phase, so it is marked inferred."}]},"fs-sync-vs-async":{"id":"fs-sync-vs-async","title":"fs sync vs async","name":"fs-sync-vs-async.js","module":"commonjs","text":"// Shows: fs.*Sync blocks and returns the result in place; the callback\n// version returns immediately and delivers the result later.\n// Why: readFileSync runs the whole read on the main thread before the next\n// line. fs.stat hands the work to the thread pool, so the line after it runs\n// first and the callback is delivered from the poll phase of the event loop.\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\n\nconst dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-map-corpus-'));\nconst file = path.join(dir, 'data.txt');\nfs.writeFileSync(file, 'twelve bytes');\n\nconsole.log('sync result: ' + fs.readFileSync(file, 'utf8'));\nfs.stat(file, (err, st) => {\n console.log('async stat callback: size=' + st.size);\n fs.rmSync(dir, { recursive: true, force: true });\n});\nconsole.log('after fs.stat call (callback not run yet)');\n","racy":false,"output":["sync result: twelve bytes","after fs.stat call (callback not run yet)","async stat callback: size=12"],"recording":"rec/fs-sync-vs-async.nmrec.gz","steps":[{"index":30,"title":"Sync: on the main thread","text":"readFileSync has already returned the text. Node reported its open, read and close as work done on the main thread (see the Events tab), and nothing went to the thread pool."},{"index":37,"title":"Async: a request for the pool","text":"fs.stat created a request, the \"fs.stat\" chip, handed it to the thread pool, and returned at once."},{"index":39,"title":"The script does not wait","text":"The next line prints before the result of stat exists: the request is still listed under \"Requests with the pool\"."},{"index":49,"title":"The callback comes from the loop","text":"The result arrives on a turn of the loop, and the callback runs (on Windows in the pending phase after poll; inferred). For a request like stat, Node reports nothing about pool threads, so the Thread pool tab cannot say which thread ran it."}]}},"prev":{"id":"staying-alive","title":"What keeps a process alive"},"next":{"id":"four-threads-six-jobs","title":"The thread pool: four threads, six jobs"}}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"save-and-share","chapter":"start","title":"Saving, opening and sharing a run","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.","blocks":[{"t":"p","text":["By the end of this lesson you can save a run, open it again, and share it, and you know that opening one is always safe."]},{"t":"h","level":2,"id":"save","text":"Save"},{"t":"p","text":["When a run has finished, ",{"t":"ui","text":"Save"}," writes its recording to a file. The file holds everything Node reported during the run and, if you choose, the text of your program."]},{"t":"note","kind":"warn","text":["A recording can contain file paths your program used, for example the folder of a file it read, and those paths can include your user name. Look before you share a recording of a program that touches your files."]},{"t":"h","level":2,"id":"open","text":"Open"},{"t":"p","text":[{"t":"ui","text":"Open"}," opens a recording file. The same file opens in the local app and on the player website, on a computer or a phone."]},{"t":"p","text":["Opening a recording replays it. A recording is data, so one from someone else is safe to open on your computer."]},{"t":"h","level":2,"id":"share","text":"Share"},{"t":"p","text":[{"t":"ui","text":"Share"}," turns a small recording into a link. The whole run is packed into the part of the link after the ",{"t":"code","text":"#"},", which browsers keep inside your own browser."]},{"t":"p","text":["A bigger run travels as a file instead, and the app tells you when that is the case."]},{"t":"image","src":"img/save-and-share.webp","alt":"Saving and sharing a run","width":1280,"height":800,"caption":"Save keeps the run as a file; Share packs a small run into a link."},{"t":"note","kind":"tip","text":["Recordings are a good way to ask a question about Node: \"why does this print in this order?\" comes with the exact run you saw."]},{"t":"note","kind":"honest","text":["A recording shows one run. Where a program has a race, run it a few times to see how often each order comes up."]},{"t":"check","question":["A friend sends you a recording link. Can opening it run code on your computer?"],"answer":["No. Opening a recording or a link only replays what was recorded. Code runs only when you press Run in your own local app."]}],"examples":{},"prev":{"id":"breakpoints","title":"Stopping at a line, and stepping"},"next":{"id":"call-stack","title":"One thing at a time, to the end"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"slow-handler","chapter":"networking","title":"A slow handler blocks everyone, and the fix","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.","blocks":[{"t":"p","text":["By the end of this lesson you can recognise a handler that blocks a server and change it so that other requests get answered meanwhile."]},{"t":"h","level":2,"id":"the-problem","text":"The problem"},{"t":"example","example":"http-blocking"},{"t":"p","text":["The ",{"t":"code","text":"/heavy"}," handler computes for 100 ms on the main thread. Just before that it asks for ",{"t":"code","text":"/light"},"."]},{"t":"list","ordered":false,"items":[["While the handler computes, nothing else in the process runs. The client of ",{"t":"code","text":"/light"}," cannot even open its connection: its connect request appears only after the work is done."],["So ",{"t":"code","text":"/light"}," is answered after ",{"t":"code","text":"/heavy"},", although it needs almost no work."]]},{"t":"h","level":2,"id":"the-fix-slices","text":"The fix: slices"},{"t":"example","example":"http-blocking-fixed"},{"t":"p","text":["The same 100 ms of work, in ten slices of 10 ms, each scheduled with ",{"t":"code","text":"setImmediate"},". Between slices the event loop runs its other phases: the connection for ",{"t":"code","text":"/light"}," is opened, its request is read, and it is answered before ",{"t":"code","text":"/heavy"}," is finished."]},{"t":"note","kind":"tip","text":["Slices keep a server responsive, but they do not make the work faster. For heavy work on the CPU, the usual answer is a worker thread or a separate process. For work Node can do on the thread pool, such as hashing or compression, use the asynchronous API."]},{"t":"note","kind":"honest","text":["nodejs-map runs worker threads, and shows the messages they send to the main thread. A view inside a worker itself is still to come."]},{"t":"check","question":["In the fixed version, could ",{"t":"code","text":"/light"}," still wait up to 10 ms?"],"answer":["Yes. If its data arrives while a slice is running, it waits for the rest of that slice before the loop can read it."]}],"examples":{"http-blocking":{"id":"http-blocking","title":"One busy handler holds up everyone","name":"http-blocking.js","module":"commonjs","text":"// A handler that does 100 ms of CPU work holds up every other request until it is done.\nconst http = require('http');\nlet port;\nlet lightSent;\n\nconst server = http.createServer((req, res) => {\n if (req.url === '/heavy') {\n console.log('server: /heavy received; a second client asks for /light now');\n get('/light');\n const t = Date.now();\n while (Date.now() - t < 100) {} // 100 ms of CPU work on the main thread\n }\n res.end(req.url);\n});\n\nfunction get(path) {\n if (path === '/light') lightSent = Date.now();\n http.get({ host: '127.0.0.1', port, path, agent: false }, (res) => {\n res.resume();\n res.on('end', () => {\n if (path === '/heavy') return console.log('client: /heavy answered');\n console.log('client: /light waited at least 100 ms = ' + (Date.now() - lightSent >= 100));\n server.close();\n });\n });\n}\nserver.listen(0, '127.0.0.1', () => {\n port = server.address().port;\n get('/heavy');\n});\n","racy":false,"output":["server: /heavy received; a second client asks for /light now","client: /heavy answered","client: /light waited at least 100 ms = true"],"recording":"rec/http-blocking.nmrec.gz","steps":[{"index":65,"title":"/heavy starts its work","text":"The /heavy handler asks for /light and then computes for 100 ms."},{"index":89,"title":"/light could not even start","text":"The connection for /light was only requested after the CPU work: its \"TCP connect\" chip appears about 100 ms after /light was asked for."},{"index":270,"title":"/light waited","text":"So /light was answered only after /heavy."}]},"http-blocking-fixed":{"id":"http-blocking-fixed","title":"The same work in slices","name":"http-blocking-fixed.js","module":"commonjs","text":"// The fix: do the heavy work in 10 ms slices with setImmediate, so other requests get a turn.\nconst http = require('http');\nlet port;\nconst answered = [];\n\nconst server = http.createServer((req, res) => {\n if (req.url !== '/heavy') return res.end(req.url);\n console.log('server: /heavy received; a second client asks for /light now');\n get('/light');\n let slices = 0;\n (function slice() {\n const t = Date.now();\n while (Date.now() - t < 10) {} // 10 ms of the work\n if (++slices < 10) setImmediate(slice);\n else res.end('/heavy');\n })();\n});\n\nfunction get(path) {\n http.get({ host: '127.0.0.1', port, path, agent: false }, (res) => {\n res.resume();\n res.on('end', () => {\n answered.push(path);\n if (answered.length < 2) return;\n console.log('client: answered in this order: ' + answered.join(', '));\n server.close();\n });\n });\n}\nserver.listen(0, '127.0.0.1', () => {\n port = server.address().port;\n get('/heavy');\n});\n","racy":false,"output":["server: /heavy received; a second client asks for /light now","client: answered in this order: /light, /heavy"],"recording":"rec/http-blocking-fixed.nmrec.gz","steps":[{"index":99,"title":"The first slice","text":"The work now runs in 10 ms slices; each \"setImmediate\" chip is the next slice."},{"index":338,"title":"/light is answered first","text":"Between slices the loop served the /light request, so it was answered before /heavy."}]}},"prev":{"id":"keep-alive","title":"Keep-alive"},"next":{"id":"streams-basics","title":"Readable, writable, transform in ten lines"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"splitting-work","chapter":"thread-pool","title":"Splitting work with setImmediate","summary":"Cut long work into slices and schedule each slice with setImmediate. Between slices the event loop runs timers and I/O.","blocks":[{"t":"p","text":["By the end of this lesson you can split a long computation so that the rest of the program keeps working while it runs."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"split-work"},{"t":"p","text":["Four slices of 5 ms each. Each slice schedules the next with ",{"t":"code","text":"setImmediate"},". Slice 1 also sets a 1 ms timer."]},{"t":"h","level":2,"id":"what-you-saw","text":"What you saw"},{"t":"list","ordered":false,"items":[["Each slice runs in the check phase, then returns. The event loop goes on with its turn: the close phase, the timers phase, then the I/O of the next turn."],["The timer is due before slice 1 ends, and it runs between slice 1 and slice 2, not after all the work."],["Four slices, four turns of the loop. The total work takes a little longer, but nothing waits for all of it."]]},{"t":"note","kind":"warn","text":["Use ",{"t":"code","text":"setImmediate"},", or a timer, for the slices: those give the loop a turn in between. ",{"t":"code","text":"process.nextTick"}," or a promise would run the next slice before the loop gets that turn, exactly like one long loop."]},{"t":"check","question":["You split 200 ms of work into 20 slices of 10 ms with ",{"t":"code","text":"setImmediate"},". A request arrives during the work. About how long does it wait before its handler can start?"],"answer":["At most about 10 ms: the rest of the current slice. Then the loop reaches its I/O step and can read the request."]}],"examples":{"split-work":{"id":"split-work","title":"Slicing work with setImmediate","name":"split-work.js","module":"commonjs","text":"// Split long work into slices with setImmediate, so other callbacks get a turn in between.\nlet slice = 0;\n\nfunction work() {\n if (slice === 0) setTimeout(() => console.log(' timer 1 ms: ran between two slices'), 1);\n const t = Date.now();\n while (Date.now() - t < 5) {\n // 5 ms of work per slice\n }\n slice += 1;\n console.log('slice ' + slice + ' done');\n if (slice < 4) setImmediate(work);\n}\n\nsetImmediate(work);\n","racy":false,"output":["slice 1 done"," timer 1 ms: ran between two slices","slice 2 done","slice 3 done","slice 4 done"],"recording":"rec/split-work.nmrec.gz","steps":[{"index":27,"title":"Slice 1","text":"The first slice set a 1 ms timer at its start and then worked for 5 ms, so the timer is already due when the slice ends."},{"index":41,"title":"The timer gets its turn","text":"Between slice 1 and slice 2 the loop passes its timers phase, and the timer runs."},{"index":91,"title":"One slice per turn","text":"Each slice ran in the check phase of its own loop turn: four slices, four turns."}]}},"prev":{"id":"blocking-the-loop","title":"Blocking the loop with CPU work"},"next":{"id":"tcp-step-by-step","title":"A TCP server and client, step by step"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"staying-alive","chapter":"event-loop","title":"What keeps a process alive","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.","blocks":[{"t":"p","text":["By the end of this lesson you can explain why a program ends when it does, how to tell Node that a timer should not keep the program running, and what ",{"t":"code","text":"'beforeExit'"}," and ",{"t":"code","text":"'exit'"}," change."]},{"t":"h","level":2,"id":"the-rule","text":"The rule"},{"t":"p","text":["After each turn, the event loop asks: can anything still call back? Active timers, open sockets and servers, and requests that wait for an answer all count. These are the handles and requests of the big picture."]},{"t":"p","text":["If nothing counts, the loop ends, and so does the process."]},{"t":"h","level":2,"id":"an-interval-that-stops-itself","text":"An interval that stops itself"},{"t":"example","example":"interval-and-clear"},{"t":"p","text":["A ",{"t":"code","text":"setInterval"}," keeps the process alive. After its third run, ",{"t":"code","text":"clearInterval"}," removes it. Nothing is left, and the process exits."]},{"t":"h","level":2,"id":"a-timer-that-lets-the-program-end","text":"A timer that lets the program end"},{"t":"p","text":["A timer can be ",{"t":"strong","text":"unref'd"},": Node leaves it out of the count when it decides whether to keep the process alive. The timer still exists, and still fires if the process is still running when it is due. ",{"t":"code","text":"timer.unref()"}," does this, and ",{"t":"code","text":"timer.ref()"}," makes the timer count again."]},{"t":"example","example":"unref-timer"},{"t":"p","text":["The program sets three timers: 1000 ms and 5 ms, both unref'd, and a normal 20 ms timer."]},{"t":"p","text":["The unref'd 5 ms timer fires, because the normal 20 ms timer keeps the process alive long enough. The unref'd 1000 ms timer never fires. When the 20 ms timer is done, nothing that counts is left, and the process exits with that timer still waiting."]},{"t":"h","level":2,"id":"beforeexit-and-exit","text":"beforeExit and exit"},{"t":"example","example":"beforeexit-and-exit"},{"t":"p","text":["When the loop has run out of work, Node emits ",{"t":"code","text":"'beforeExit'"}," on ",{"t":"code","text":"process"},". A listener may start new work, which keeps the process going. Then ",{"t":"code","text":"'beforeExit'"}," comes again when that work is done."]},{"t":"p","text":[{"t":"code","text":"'exit'"}," is final. In an ",{"t":"code","text":"'exit'"}," listener only code that runs right away still runs. A timer set there never fires."]},{"t":"note","kind":"tip","text":["A server that stays alive after its work is done usually has a socket or a timer still open. Look at ",{"t":"ui","text":"Queues"}," at the end of the run. Whatever is still listed under Timers or Pending I/O is what kept the process alive, unless it was unref'd."]},{"t":"check","question":["A program's only remaining work is an unref'd ",{"t":"code","text":"setInterval"}," and an ",{"t":"code","text":"fs.readFile"}," that has not finished. Does the process exit before the file has been read?"],"answer":["No. The file request counts, so the process stays until its callback has run. After that only the unref'd interval is left, and the process exits."]}],"examples":{"interval-and-clear":{"id":"interval-and-clear","title":"setInterval and clearInterval","name":"interval-clear.js","module":"commonjs","text":"// Shows: setInterval repeating until clearInterval, and that clearing the last\n// timer lets the process exit by itself.\n// Why: an active interval keeps the event loop alive and is re-armed after\n// each run. Calling clearInterval inside its own callback stops it; with no\n// other handles left, the loop is empty, so Node emits 'exit' and ends.\nlet n = 0;\nconst timer = setInterval(() => {\n n += 1;\n console.log('interval run ' + n);\n if (n === 3) {\n clearInterval(timer);\n console.log('interval cleared');\n }\n}, 5);\nprocess.on('exit', () => console.log('exit'));\n","racy":false,"output":["interval run 1","interval run 2","interval run 3","interval cleared","exit"],"recording":"rec/interval-and-clear.nmrec.gz","steps":[{"index":17,"title":"One repeating timer","text":"setInterval created a single timer that repeats every 5 ms. Timers shows it waiting as \"setInterval 5 ms\"."},{"index":34,"title":"Back in the list after a run","text":"The first run has finished, and the same timer is back in the list of timers. Node did not report this: nodejs-map infers it, because the timer repeats and was not cleared."},{"index":65,"title":"The third run clears it","text":"The same timer runs a third time, in its own timers phase, and its callback calls clearInterval."},{"index":77,"title":"Taken out of the list","text":"clearInterval removed the timer, so Timers is empty, and the loop has nothing left to wait for (inferred from the timer being removed before it ran again)."},{"index":82,"title":"exit","text":"Node emits 'exit' and the process ends. No callback is on the main thread: an 'exit' listener is called directly, not as a callback from a queue."}]},"unref-timer":{"id":"unref-timer","title":"unref: a timer that does not keep the process alive","name":"unref-timer.js","module":"commonjs","text":"// Shows: an unref'd timer does not keep the process alive.\n// Why: unref() tells Node not to count the timer as a reason to keep the loop\n// running. The 1000 ms timer never fires: when the last ref'd timer (20 ms)\n// is done, the loop has nothing left that counts and the process exits.\n// The 5 ms unref'd timer does fire, because the ref'd 20 ms timer keeps the\n// loop alive for long enough.\nconst never = setTimeout(() => console.log('unref 1000ms fired (never)'), 1000);\nnever.unref();\nconst early = setTimeout(() => console.log('unref 5ms fired'), 5);\nearly.unref();\nsetTimeout(() => console.log('ref 20ms fired'), 20);\nconsole.log('hasRef: never=' + never.hasRef() + ' early=' + early.hasRef());\nprocess.on('exit', () => console.log('exit'));\n","racy":false,"output":["hasRef: never=false early=false","unref 5ms fired","ref 20ms fired","exit"],"recording":"rec/unref-timer.nmrec.gz","steps":[{"index":25,"title":"Three timers","text":"Three timers wait under Timers: 1000 ms and 5 ms, both unref'd, and 20 ms."},{"index":41,"title":"An unref'd timer still fires","text":"The 5 ms timer fires: the 20 ms timer keeps the process alive long enough."},{"index":61,"title":"Exit with a timer still waiting","text":"After the 20 ms timer only the unref'd 1000 ms timer is left, and it does not count. The process exits; Timers still shows it waiting."}]},"beforeexit-and-exit":{"id":"beforeexit-and-exit","title":"beforeExit and exit","name":"beforeexit-exit.js","module":"commonjs","text":"// Shows: process 'beforeExit' vs 'exit'. Deterministic.\n// Why: when the event loop has nothing left, Node emits 'beforeExit'. A\n// listener may schedule more work, which restarts the loop; 'beforeExit' is\n// emitted again when that work is done. 'exit' is emitted last, once, and\n// only synchronous code can run in it: the timer scheduled there never fires.\nlet beforeExitCount = 0;\nprocess.on('beforeExit', (code) => {\n beforeExitCount += 1;\n console.log('beforeExit #' + beforeExitCount + ' code=' + code);\n if (beforeExitCount === 1) {\n setTimeout(() => console.log('timer scheduled from beforeExit'), 1);\n }\n});\nprocess.on('exit', (code) => {\n console.log('exit code=' + code);\n setTimeout(() => console.log('never printed'), 0);\n});\nsetTimeout(() => console.log('main timer'), 1);\nconsole.log('sync end');\n","racy":false,"output":["sync end","main timer","beforeExit #1 code=0","timer scheduled from beforeExit","beforeExit #2 code=0","exit code=0"],"recording":"rec/beforeexit-and-exit.nmrec.gz","steps":[{"index":30,"title":"The last timer","text":"The main timer runs. It was the program's last waiting work: Timers, Immediates and Pending I/O are empty."},{"index":45,"title":"beforeExit","text":"With the loop out of work, Node emits 'beforeExit'. A beforeExit listener is not called from a queue, so the main thread shows nothing running. The Events tab shows what Node reported."},{"index":52,"title":"More work from beforeExit","text":"The listener set a new timer, the \"setTimeout 1 ms\" chip under Timers, so the loop has work again and keeps going."},{"index":59,"title":"The new timer runs","text":"The timer set from beforeExit runs in a timers phase, like any other."},{"index":74,"title":"beforeExit again","text":"The loop is empty again, so 'beforeExit' is emitted a second time. This time the listener sets nothing."},{"index":87,"title":"exit: too late for timers","text":"Now Node emits 'exit'. The exit listener sets a timer, and Timers shows it waiting (\"setTimeout 1 ms\"), but the process ends without running it."}]}},"prev":{"id":"timeout-vs-immediate","title":"setTimeout(0) or setImmediate?"},"next":{"id":"reading-a-file","title":"Reading a file: one trip through the thread pool"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"stepping-into-node","chapter":"under-the-hood","title":"Debugging Node's own JavaScript","summary":"Step from your code into node:internal files and watch Node's JavaScript library do its work, with the map following along.","blocks":[{"t":"p","text":["By the end of this lesson you can step from your own code into Node's JavaScript library and find where you are on the map."]},{"t":"h","level":2,"id":"node-is-partly-javascript","text":"Node is partly JavaScript"},{"t":"p","text":["A large part of Node is JavaScript: ",{"t":"code","text":"fs"},", ",{"t":"code","text":"timers"},", ",{"t":"code","text":"streams"},", ",{"t":"code","text":"net"}," and ",{"t":"code","text":"http"}," are written in JavaScript and run on V8 like your code. In stack traces their files appear as ",{"t":"code","text":"node:fs"},", ",{"t":"code","text":"node:internal/timers"}," and so on. The debugger can step into them."]},{"t":"h","level":2,"id":"step-into-fs-readfile","text":"Step into fs.readFile"},{"t":"example","example":"readfile-thread-pool"},{"t":"list","ordered":true,"items":[["Click ",{"t":"ui","text":"the line numbers"}," next to the ",{"t":"code","text":"fs.readFile(...)"}," line."],["Press ",{"t":"ui","text":"Run"},". The program stops before the call."],["Press ",{"t":"ui","text":"Step into next function call"},". You are now in ",{"t":"code","text":"node:fs"},", inside ",{"t":"code","text":"readFile"},". ",{"t":"ui","text":"Stack"}," shows your line below Node's."],["Keep stepping with ",{"t":"ui","text":"Step over next function call"}," and ",{"t":"ui","text":"Step into next function call"},", and ",{"t":"ui","text":"Step out of current function"}," to go back up."]]},{"t":"p","text":["The map shows where the paused line is: in Node's JavaScript library, in the file you are stepping through."]},{"t":"image","src":"img/paused-in-node-fs.webp","alt":"Paused inside node:fs","width":1280,"height":800,"caption":"Stepping into fs.readFile opens Node's own JavaScript."},{"t":"note","kind":"warn","text":["Stepping through ",{"t":"code","text":"lib/"}," takes many steps: Node checks every argument carefully. Use ",{"t":"ui","text":"Step out of current function"}," when you have seen enough of a function."]},{"t":"note","kind":"honest","text":["The debugger stops only JavaScript. When you step into the place where ",{"t":"code","text":"lib/fs.js"}," calls into C++, the C++ side and libuv run without stopping, and the work on the thread pool happens while you are paused."]},{"t":"check","question":["You step into ",{"t":"code","text":"fs.readFile"}," and keep pressing step over until the function returns. Has the file been read when it returns?"],"answer":["Not necessarily. ",{"t":"code","text":"readFile"}," only hands the job to the thread pool and returns; the file is read on a pool thread, and your callback runs later from the event loop."]}],"examples":{"readfile-thread-pool":{"id":"readfile-thread-pool","title":"Reading a file: one trip through the thread pool","name":"readfile-callback.js","module":"commonjs","text":"// Shows: the callback path of fs.readFile. Deterministic.\n// Why: readFile returns at once. In Node 26 a small file is read as ONE\n// thread pool job: a pool thread opens, stats, reads and closes the file,\n// then hands the result back to the event loop. So the rest of the script\n// runs first, then the nextTick, and the readFile callback comes later,\n// when the loop picks the finished job up. (Its order relative to\n// setImmediate is NOT guaranteed: see readfile-vs-immediate.js.)\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\n\nconst dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-map-corpus-'));\nconst file = path.join(dir, 'data.txt');\nfs.writeFileSync(file, 'hello world');\n\nfs.readFile(file, 'utf8', (err, text) => {\n console.log('readFile callback: err=' + err + ' text=' + text);\n fs.rmSync(dir, { recursive: true, force: true });\n});\nprocess.nextTick(() => console.log('nextTick'));\nconsole.log('sync: after calling readFile');\n","racy":false,"output":["sync: after calling readFile","nextTick","readFile callback: err=null text=hello world"],"recording":"rec/readfile-thread-pool.nmrec.gz","steps":[{"index":25,"title":"One job for the pool","text":"fs.readFile created a request, the \"fs.readFile\" chip, and handed one job to the thread pool. Open the Thread pool tab."},{"index":30,"title":"A pool thread starts it","text":"A pool thread reported starting an \"fs.readfile\" job (observed). That it is this job is inferred. Reports from pool threads reach nodejs-map late, so where they sit against the main thread is approximate."},{"index":34,"title":"The thread is done","text":"The pool thread has finished. Open, read and close all happened there, in one job. The result now waits under \"Finished, not delivered\" until the main thread is free and the loop picks it up."},{"index":54,"title":"The callback runs","text":"The loop delivers the result, and the callback runs on the main thread. The script's last line and the tick came earlier, as always. On Windows this happens in the pending phase right after poll; Node did not report the phase, so it is marked inferred."}]}},"prev":{"id":"microtasks-belong-to-v8","title":"The microtask queue belongs to V8"},"next":{"id":"probe-build","title":"The probe build: stopping between phases"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"streams-basics","chapter":"streams","title":"Readable, writable, transform in ten lines","summary":"A readable stream produces chunks, a transform changes them, a writable consumes them. pipeline connects them and moves one chunk at a time.","blocks":[{"t":"p","text":["By the end of this lesson you can name the three kinds of objects that Node uses to move data piece by piece, and say how the pieces move through a pipeline."]},{"t":"h","level":2,"id":"what-a-stream-is","text":"What a stream is"},{"t":"p","text":["A ",{"t":"strong","text":"stream"}," is an object that hands over data a piece at a time, instead of all at once. Each piece is called a ",{"t":"strong","text":"chunk"},". Files, sockets and HTTP bodies are all read and written as streams in Node, so a program can work through a file of any size a chunk at a time."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"streams-memory"},{"t":"p","text":["A readable stream made from three strings, a transform that turns them to upper case, and a writable stream that prints them."]},{"t":"h","level":2,"id":"what-you-see","text":"What you see"},{"t":"list","ordered":false,"items":[["A ",{"t":"strong","text":"readable"}," stream produces chunks. Here ",{"t":"code","text":"Readable.from"}," turns an array into one."],["A ",{"t":"strong","text":"transform"}," stream is readable and writable at once: it takes a chunk in, and passes a changed chunk on."],["A ",{"t":"strong","text":"writable"}," stream consumes chunks. Here its ",{"t":"code","text":"write"}," function prints each chunk, then calls ",{"t":"code","text":"cb()"}," to say \"done, send the next one\"."],[{"t":"code","text":"pipeline"}," connects them. Nothing moves until the script has ended. Then each chunk is transformed and written before the next one goes through."],["With no I/O in this program, every callback comes from the nextTick queue, the microtask queue, or the streams' own end-of-stream callbacks."]]},{"t":"note","kind":"tip","text":["Real streams usually wrap I/O: files, sockets, HTTP bodies. The rules are the same. The chunks just arrive from the event loop's I/O phases instead of from a queue."]},{"t":"check","question":["In the writable stream's ",{"t":"code","text":"write"}," function, what happens if you forget to call ",{"t":"code","text":"cb()"},"?"],"answer":["The writable never asks for the next chunk. The pipeline stops after the first chunk, and its callback is never called."]}],"examples":{"streams-memory":{"id":"streams-memory","title":"Readable, Transform, Writable","name":"streams-memory.js","module":"commonjs","text":"// Shows: a small Readable -> Transform -> Writable pipeline in memory.\n// Why this order: stream.pipeline moves one chunk at a time and respects\n// backpressure. Each chunk is read, transformed, then written before the next\n// is pulled, and 'finish' fires after the last write. No I/O is involved, so\n// everything runs from promise and nextTick queues; the order was observed to\n// be stable over many runs (see README) rather than guaranteed by a spec.\nconst { Readable, Transform, Writable, pipeline } = require('stream');\n\nconst source = Readable.from(['a', 'b', 'c']);\nconst upper = new Transform({\n transform(chunk, enc, cb) {\n console.log('transform ' + chunk);\n cb(null, chunk.toString().toUpperCase());\n },\n});\nconst sink = new Writable({\n write(chunk, enc, cb) {\n console.log('write ' + chunk);\n cb();\n },\n});\n\npipeline(source, upper, sink, (err) => console.log('pipeline done: err=' + err));\nconsole.log('sync: pipeline started');\n","racy":false,"output":["sync: pipeline started","transform a","write A","transform b","write B","transform c","write C","pipeline done: err=undefined"],"recording":"rec/streams-memory.nmrec.gz","steps":[{"index":27,"title":"Set up, nothing moved yet","text":"pipeline() connected the three streams and returned. No chunk has moved yet."},{"index":43,"title":"One chunk at a time","text":"Each chunk is transformed and then written before the next one goes through."},{"index":133,"title":"Done","text":"After the last write, pipeline calls back once. The event loop never entered a phase in this run: every callback came from the nextTick queue, the microtask queue, or the streams' own end-of-stream callbacks."}]}},"prev":{"id":"slow-handler","title":"A slow handler blocks everyone, and the fix"},"next":{"id":"backpressure","title":"Backpressure made visible"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"tcp-step-by-step","chapter":"networking","title":"A TCP server and client, step by step","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.","blocks":[{"t":"p","text":["By the end of this lesson you can follow a TCP connection through the event loop: which callbacks run, in which phase, and what waits in between."]},{"t":"h","level":2,"id":"the-program","text":"The program"},{"t":"example","example":"tcp-round-trip"},{"t":"p","text":["A server and a client in one program, on 127.0.0.1, with a port chosen by the operating system. The client sends \"ping\", the server answers \"pong\", and both close."]},{"t":"p","text":["Step through it with ",{"t":"ui","text":"Queues"}," open. Network requests wait in a queue of their own there, Pending I/O: requests that wait for the operating system to answer."]},{"t":"h","level":2,"id":"what-you-saw","text":"What you saw"},{"t":"list","ordered":false,"items":[[{"t":"code","text":"listen"}," and ",{"t":"code","text":"connect"}," ask the operating system for a socket. The connect request waits under Pending I/O until the operating system answers."],["The operating system, not the thread pool, watches the sockets. In the poll phase the event loop asks it which sockets are ready, and libuv calls back for each ready one. ",{"t":"ui","text":"Thread pool"}," stays empty for socket work."],["A connection arriving at the server, data arriving at a socket, and the end of a connection each start a callback. In this Windows recording they run in the pending phase right after poll. On Linux and macOS they run in poll."],[{"t":"code","text":"socket.end()"}," sends the end of the data and creates a shutdown request, which also waits under Pending I/O."],["Once a socket is closed, its ",{"t":"code","text":"'close'"}," event comes from the close phase at the end of the turn."]]},{"t":"p","text":["All of this happens on the main thread, one callback at a time."]},{"t":"note","kind":"honest","text":["What you see for sockets today: connect, write and shutdown requests in Pending I/O, and the callbacks of sockets and servers. Bytes, buffers and the operating system's own queues are a later addition."]},{"t":"check","question":["The client writes \"ping\" and the server answers at once in its data callback. Can \"client: got pong\" run in the same loop step as \"server: got ping\"?"],"answer":["Not in this recording. The answer has to travel back through the operating system, and the client's socket is read in the poll phase of a later turn."]}],"examples":{"tcp-round-trip":{"id":"tcp-round-trip","title":"A local TCP round trip (pending I/O)","name":"net-roundtrip.js","module":"commonjs","text":"// Shows: a TCP server and client talking over 127.0.0.1 on an OS-chosen port\n// (port 0), then both closing so the process exits by itself.\n// Why this order: every printed line is caused by the one before it\n// (listening -> connection -> data -> reply -> close), so the order is fixed\n// by the protocol. Lines that would be unordered (the client's 'connect' vs\n// the server's 'connection', the two sides' 'close') are deliberately not\n// printed. The port number varies and is not printed.\nconst net = require('net');\n\nconst server = net.createServer((socket) => {\n console.log('server: connection');\n socket.on('data', (chunk) => {\n console.log('server: got ' + chunk.toString());\n socket.end('pong');\n });\n});\n\nserver.listen(0, '127.0.0.1', () => {\n console.log('server: listening');\n const client = net.connect(server.address().port, '127.0.0.1', () => client.write('ping'));\n client.on('data', (chunk) => console.log('client: got ' + chunk.toString()));\n client.on('close', () => {\n console.log('client: closed');\n server.close(() => console.log('server: closed'));\n });\n});\n","racy":false,"output":["server: listening","server: connection","server: got ping","client: got pong","client: closed","server: closed"],"recording":"rec/tcp-round-trip.nmrec.gz","steps":[{"index":26,"title":"The server is listening","text":"The listen callback runs, and starts the client."},{"index":41,"title":"A connect request waits","text":"net.connect created a connect request, the \"TCP connect\" chip under Pending I/O. It waits there until the operating system answers; that it waits there is inferred."},{"index":49,"title":"The server sees the connection","text":"The server's connection callback runs. Node did not report the phase. On Windows, the poll phase only collects socket events, and their callbacks run right after it, so the screen shows \"pending (after poll)\", marked inferred."},{"index":62,"title":"The client is connected","text":"The connect request completes and leaves Pending I/O. Its callback writes \"ping\"."},{"index":71,"title":"ping arrives","text":"On a later turn of the loop, the server's socket has data. Its callback prints it and answers \"pong\"."},{"index":100,"title":"pong arrives","text":"The client's socket gets \"pong\" on a later turn. The server had already asked to close its side with socket.end(): a shutdown request appeared under Pending I/O."},{"index":140,"title":"The client's close callback","text":"The client's socket has closed, and its close callback runs in the close phase, near the end of the turn. Node did not report this phase: nodejs-map knows this is a close callback because close() was called on the handle (inferred)."},{"index":166,"title":"The server closes","text":"The server's 'close' event comes through a tick (see the Stack tab), added by the server's own code. Nothing is left waiting, and the process exits."}]}},"prev":{"id":"splitting-work","title":"Splitting work with setImmediate"},"next":{"id":"many-clients","title":"Many clients on one thread"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"the-map","chapter":"start","title":"The map: where in Node is this?","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.","blocks":[{"t":"p","text":["By the end of this lesson you can find on the map where a piece of your program's work happens inside Node, and open the exact lines of Node's source code behind it."]},{"t":"h","level":2,"id":"what-the-map-shows","text":"What the map shows"},{"t":"p","text":[{"t":"ui","text":"the map"}," is Node itself, drawn as boxes inside boxes. It has the layers of the big picture: your code at the top, then Node's JavaScript library (",{"t":"code","text":"lib/"},"), the C++ bindings (",{"t":"code","text":"src/"},"), V8 and libuv, and the operating system at the bottom."]},{"t":"p","text":["From far away you see only those big parts. Closer in you see their subsystems, then single files, then single functions."]},{"t":"p","text":["Every box comes from Node's real source code, at the version that runs: each one has a file and a range of lines."]},{"t":"h","level":2,"id":"moving-around","text":"Moving around"},{"t":"list","ordered":false,"items":[["Drag, or scroll, to move."],["Pinch, or hold ",{"t":"kbd","text":"Ctrl"}," and scroll, to zoom. ",{"t":"ui","text":"Zoom in"},", ",{"t":"ui","text":"Zoom out"}," and ",{"t":"ui","text":"Show the whole map"}," do the same with buttons."],[{"t":"ui","text":"Search files and functions"}," finds a file or a function by name and flies there."],["Right-click a box for a card with its description, its file and lines, and buttons that open its code."]]},{"t":"p","text":["During a run, the boxes where work happens light up. With ",{"t":"ui","text":"Move map with the run"}," on, the map follows the run. With it off, the map stays where you put it, and ",{"t":"ui","text":"Show on map"}," flies to the current place once."]},{"t":"h","level":2,"id":"follow-one-call-through-node","text":"Follow one call through Node"},{"t":"example","example":"first-run"},{"t":"p","text":["A ",{"t":"strong","text":"call path"}," is a list of the functions that one call goes through inside Node, picked out by hand from Node's source code and drawn on the map. Each stop on the path names a function and opens its lines."]},{"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"},". The map draws the path that a ",{"t":"code","text":"setTimeout"}," call takes through Node: from ",{"t":"code","text":"setTimeout"}," in Node's JavaScript library, through a C++ binding, to libuv's timer, and back to your callback."]},{"t":"image","src":"img/map-call-path.webp","alt":"A call path on the map","width":1280,"height":800,"caption":"Each stop of a call path opens the exact lines in Node's source code."},{"t":"p","text":["The code opens in ",{"t":"ui","text":"Source"},", the tab for Node's own source code. It offers a link to the same lines on GitHub, at the exact version of Node that ran."]},{"t":"note","kind":"honest","text":["Lit boxes come from what was recorded, and carry the same marks as everything else. A call path is a different kind of claim. It was traced by hand from Node's source code, so it is marked as a model: it shows what the code does, which is not the same as what your run reported."]},{"t":"check","question":["A box deep inside libuv lights up while your program runs. How do you find out which function it is, and read its code?"],"answer":["Right-click the box. Its card names the function, its file and its lines, and opens the code."]}],"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":"three-marks","title":"The three marks: observed, inferred, model"},"next":{"id":"breakpoints","title":"Stopping at a line, and stepping"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"three-marks","chapter":"start","title":"The three marks: observed, inferred, model","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.","blocks":[{"t":"p","text":["By the end of this lesson you can tell, for a fact on the screen, whether Node reported it, whether nodejs-map worked it out, or whether it is only a drawing."]},{"t":"h","level":2,"id":"why-the-marks-exist","text":"Why the marks exist"},{"t":"p","text":["Node reports a good deal about its own work: when a callback starts, when it ends, when it runs its timers. Other things, such as every step of the event loop, it keeps to itself."]},{"t":"p","text":["nodejs-map puts those together from what Node did report, and the marks tell you which kind of fact you are looking at."]},{"t":"h","level":2,"id":"the-three-marks-again","text":"The three marks, again"},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"Observed"},": Node reported it. Example: \"the timer's callback started\"."],[{"t":"strong","text":"Inferred"},": nodejs-map worked it out from what Node reported. Example: \"so this callback came from the microtask queue\"."],[{"t":"strong","text":"Model"},": a drawing that explains how something works in general. Example: a path drawn on the map to show which functions a call goes through."]]},{"t":"p","text":[{"t":"ui","text":"the three certainty marks"}," in the top bar shows how each mark is drawn. Click them for the full explanation."]},{"t":"h","level":2,"id":"two-new-tabs","text":"Two new tabs"},{"t":"p","text":["This lesson uses two more tabs of the panels:"]},{"t":"list","ordered":false,"items":[[{"t":"ui","text":"Now"}," shows what is happening at the moment you are looking at: what the main thread is running, which phase the event loop is in, and why the running callback ran."],[{"t":"ui","text":"Stack"}," lists the callbacks that are running on the main thread at this moment, and where each one came from."]]},{"t":"h","level":2,"id":"see-them-in-a-run","text":"See them in a run"},{"t":"example","example":"first-run"},{"t":"p","text":["Open the recording, and step to \"The promise callback runs\". Open ",{"t":"ui","text":"Stack"},". It says the running callback came from the microtask queue, and that fact is marked inferred. Node reported that a callback started. nodejs-map worked out which queue it came from, from the kind of callback it was."]},{"t":"p","text":["Now step to \"The timer fires\" and open ",{"t":"ui","text":"Now"},". The event loop is in its timers phase, and that phase is marked observed. Node reports, by itself, each time it runs its timers."]},{"t":"image","src":"img/marks-in-a-run.webp","alt":"An observed phase on the Now tab","width":1280,"height":800,"caption":"The timers phase here is observed: Node reported it. Click any mark for its explanation."},{"t":"h","level":2,"id":"rules","text":"Rules"},{"t":"p","text":["Every inferred fact names the ",{"t":"strong","text":"rule"}," that produced it, with a short code such as \"QP\" or \"P1w\". A rule is a written explanation: what was seen, what is concluded from it, on which systems that holds, and which lines of Node's source code it relies on."]},{"t":"p","text":["Click the mark of an inferred fact to read its rule."]},{"t":"note","kind":"honest","text":["An inferred fact can be wrong, if Node behaves differently from what its rule expects. The rules are checked against a specially built Node that reports more than the official one; the lesson ",{"t":"link","text":"How the tool knows","href":"learn:observed-and-inferred"}," explains how."]},{"t":"check","question":["The screen says a callback ran in the timers phase, and the phase has the observed mark. Did Node report that phase, or did nodejs-map work it out?"],"answer":["Node reported it. Node reports each time it runs its timers, so a timer's callback inside that report is known to be in the timers phase."]}],"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":"playback","title":"Watching a run, step by step"},"next":{"id":"the-map","title":"The map: where in Node is this?"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"timeout-vs-immediate","chapter":"event-loop","title":"setTimeout(0) or setImmediate?","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.","blocks":[{"t":"p","text":["By the end of this lesson you can explain why ",{"t":"code","text":"setTimeout(fn, 0)"}," and ",{"t":"code","text":"setImmediate(fn)"}," run in a different order from run to run in one place, and always in the same order in another."]},{"t":"h","level":2,"id":"from-the-script-a-race","text":"From the script: a race"},{"t":"example","example":"timeout-vs-immediate-main"},{"t":"p","text":["Before its first turn, the event loop runs the timers that are already due. A 0 ms timer is really a 1 ms timer."]},{"t":"list","ordered":false,"items":[["If at least 1 ms has passed between the ",{"t":"code","text":"setTimeout"}," call and that moment, the timer is due, and it runs first."],["If not, the loop goes on to the check phase, where the immediate runs. The timer runs in the timers phase at the end of that turn."]]},{"t":"p","text":["This recording went the second way. Run the program a few times on your own computer, and you will see both orders. On the computer that made these recordings, the immediate won in about 9 runs out of 10."]},{"t":"h","level":2,"id":"inside-an-i-o-callback-always-the-same-order","text":"Inside an I/O callback: always the same order"},{"t":"example","example":"timeout-vs-immediate-io"},{"t":"p","text":["The callback of ",{"t":"code","text":"fs.readFile"}," runs in the I/O part of a turn: poll on Linux and macOS, the pending phase right after poll on Windows. The next phase of the same turn is check, so the immediate runs. The timers phase comes after it."]},{"t":"p","text":["The order is the same every time, on every system."]},{"t":"note","kind":"tip","text":["Want \"after the I/O that is already waiting, before any timer\"? Use ",{"t":"code","text":"setImmediate"}," inside an I/O callback. Want \"after at least this delay\"? Use ",{"t":"code","text":"setTimeout"},". For \"as soon as the current code has finished\", reach for ",{"t":"code","text":"process.nextTick"}," or a promise."]},{"t":"check","question":["Inside an ",{"t":"code","text":"fs.readFile"}," callback you call ",{"t":"code","text":"setTimeout(a, 0)"}," first and ",{"t":"code","text":"setImmediate(b)"}," second. Does calling the timer first make it run first?"],"answer":["No, b runs first. The order of the calls does not matter: after the I/O comes the check phase of the same turn, and the timers phase only after it."]}],"examples":{"timeout-vs-immediate-main":{"id":"timeout-vs-immediate-main","title":"setTimeout(0) vs setImmediate from the main script: a race","name":"timeout-vs-immediate-main.js","module":"commonjs","text":"// Shows: setTimeout(fn, 0) vs setImmediate(fn) called from the main script.\n// RACY. The order depends on timing, not on a rule.\n// Why: a delay of 0 is stored as 1 ms. The first loop iteration runs the\n// timers phase first, and a timer is due only if at least 1 ms has passed\n// (by the loop's clock) since it was scheduled. If the process took more than\n// 1 ms between scheduling the timer and the first timers check, \"timeout\"\n// prints first; otherwise the check phase runs \"immediate\" first and the\n// timer waits for the next iteration. Machine load changes which one wins.\nsetTimeout(() => console.log('timeout 0'), 0);\nsetImmediate(() => console.log('immediate'));\n","racy":true,"output":["immediate","timeout 0"],"recording":"rec/timeout-vs-immediate-main.nmrec.gz","steps":[{"index":19,"title":"A timer and an immediate","text":"The script set a 0 ms timer, which Node stores as 1 ms, and an immediate. Queues shows a \"setTimeout 1 ms\" chip under Timers and a \"setImmediate\" chip under Immediates."},{"index":25,"title":"The check phase comes first this time","text":"The loop reached the check phase without running the timer: in this run, the 1 ms had not passed when it looked at its timers. Node reported this check phase, so it is marked observed."},{"index":39,"title":"Then the timer","text":"The timer runs in the timers phase that follows. Run the program a few times on your own computer, and you will sometimes see \"timeout 0\" first."}]},"timeout-vs-immediate-io":{"id":"timeout-vs-immediate-io","title":"setTimeout(0) vs setImmediate inside an I/O callback","name":"timeout-vs-immediate-io.js","module":"commonjs","text":"// Shows: setTimeout(fn, 0) vs setImmediate(fn) called from inside an I/O\n// callback. Deterministic: \"immediate\" always comes first.\n// Why: a file-read callback runs in the poll phase. After poll the loop goes\n// to the check phase (setImmediate callbacks), and only then wraps around to\n// the timers phase of the next iteration. So the immediate runs first no\n// matter how much time has passed.\nconst fs = require('fs');\n\nfs.readFile(__filename, () => {\n console.log('readFile callback');\n setTimeout(() => console.log('timeout 0'), 0);\n setImmediate(() => console.log('immediate'));\n});\n","racy":false,"output":["readFile callback","immediate","timeout 0"],"recording":"rec/timeout-vs-immediate-io.nmrec.gz","steps":[{"index":30,"title":"The I/O callback","text":"The \"fs.readFile\" request came back from the thread pool, and its callback runs. The screen shows \"pending (after poll)\". Node did not report this phase; nodejs-map worked it out from the kind of callback, so it is marked inferred."},{"index":41,"title":"A timer and an immediate from inside it","text":"Inside the callback, the program sets a 0 ms timer and an immediate. Queues shows \"setTimeout 1 ms\" under Timers and \"setImmediate\" under Immediates."},{"index":49,"title":"Check comes next: the immediate","text":"After the I/O, the loop goes on to the check phase, so the immediate runs. Node reported this phase, so it is marked observed."},{"index":62,"title":"Then the timers phase","text":"Only after the check phase does the loop reach its timers phase and run the timer. From an I/O callback this order is the same in every run."}]}},"prev":{"id":"loop-phases","title":"The phases of the event loop, one by one"},"next":{"id":"staying-alive","title":"What keeps a process alive"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"timers-are-not-now","chapter":"event-loop","title":"What a delay really means","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.","blocks":[{"t":"p","text":["By the end of this lesson you can predict the order of several timers, and explain why a timer often starts later than you asked."]},{"t":"h","level":2,"id":"a-delay-is-a-minimum","text":"A delay is a minimum"},{"t":"example","example":"timer-lateness"},{"t":"p","text":["The program sets a 10 ms timer, then keeps the main thread busy for about 30 ms."]},{"t":"p","text":[{"t":"code","text":"setTimeout(fn, 10)"}," means: run ",{"t":"code","text":"fn"}," once 10 ms have passed, or later. The moment the delay is over is the timer's ",{"t":"strong","text":"due time"},". When the timer really starts depends on what else the main thread is doing at that moment."]},{"t":"p","text":["Here the main thread is busy until about 30 ms. Step to the moment the timer starts. ",{"t":"ui","text":"Queues"}," shows how late it was. That number is nodejs-map's own arithmetic: the start time minus the due time."]},{"t":"h","level":2,"id":"0-ms-is-1-ms","text":"0 ms is 1 ms"},{"t":"p","text":["Node stores a delay of 0, or anything below 1, as 1 ms. That is why the chip of a ",{"t":"code","text":"setTimeout(fn, 0)"}," says \"setTimeout 1 ms\"."]},{"t":"h","level":2,"id":"in-order-of-due-time","text":"In order of due time"},{"t":"example","example":"timers-phase"},{"t":"p","text":["Five timers, with delays of 200, 100, 100, 1 and 0 ms. They run in order of due time, not in the order of the ",{"t":"code","text":"setTimeout"}," calls. Two timers with the same delay run in the order they were created."]},{"t":"p","text":["When several timers are due together, they all run in one timers phase: the phase of the event loop's turn that runs due timers."]},{"t":"note","kind":"tip","text":["Want something to run as soon as possible, after the current code? A timer is the slowest way to ask. The next two lessons show faster ways."]},{"t":"note","kind":"honest","text":["The recordings of this course were made on Windows, where short timers often started a few milliseconds late even when nothing else was running. Expect different lateness on your computer. The order is still the order of due time."]},{"t":"check","question":[{"t":"code","text":"setTimeout(a, 5); setTimeout(b, 0); setTimeout(c, 5);"}," In which order do a, b and c run?"],"answer":["b, a, c. b is due first, because its 0 ms is stored as 1 ms. a and c have the same delay, so they run in the order they were created. (Each due time counts from its own ",{"t":"code","text":"setTimeout"}," call. A pause of several milliseconds between the calls could change this.)"]}],"examples":{"timer-lateness":{"id":"timer-lateness","title":"A timer that starts late","name":"timer-lateness.js","module":"commonjs","text":"// A timer says \"not before\", not \"exactly at\": here it starts late because the script is busy.\nconst start = Date.now();\n\nsetTimeout(() => {\n const waited = Date.now() - start;\n console.log('timer: asked for 10 ms, waited at least 30: ' + (waited >= 30));\n}, 10);\n\nwhile (Date.now() - start < 30) {\n // the timer is due after 10 ms, but JavaScript is still running\n}\nconsole.log('script: done after 30 ms');\n","racy":false,"output":["script: done after 30 ms","timer: asked for 10 ms, waited at least 30: true"],"recording":"rec/timer-lateness.nmrec.gz","steps":[{"index":17,"title":"Due in 10 ms","text":"The script sets a 10 ms timer, the \"setTimeout 10 ms\" chip under Timers."},{"index":19,"title":"30 ms later, still waiting","text":"The script keeps the thread busy for about 30 ms. The timer is overdue but has to wait."},{"index":30,"title":"It runs, late","text":"The timer runs as soon as the thread is free. Timers shows how late it started; that number is nodejs-map's arithmetic from the delay, not something Node reported."}]},"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":"call-stack","title":"One thing at a time, to the end"},"next":{"id":"next-tick","title":"process.nextTick"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"tour","chapter":"before","title":"A tour of the screen","summary":"The main areas of nodejs-map, each named on one picture, with what each one is for.","blocks":[{"t":"p","text":["By the end of this lesson you can name the main areas of the screen and say what each one is for."]},{"t":"p","text":["This is a quick look around, so read it lightly. Later lessons come back to each area when you need it."]},{"t":"image","src":"img/tour-areas.webp","alt":"The main areas of nodejs-map, each one named","width":1280,"height":800,"caption":"The local app after a short run, with each main area named."},{"t":"p","text":["Click any picture in this course to enlarge it. In the enlarged picture you can zoom with the mouse wheel or by pinching, as on the map. Press ",{"t":"kbd","text":"Escape"}," or click × to close it."]},{"t":"h","level":2,"id":"the-top-bar","text":"The top bar"},{"t":"p","text":[{"t":"ui","text":"the top bar"}," runs along the top of the screen. It holds what is about the whole app rather than one area."]},{"t":"list","ordered":false,"items":[[{"t":"ui","text":"the Map / Learn switch"}," moves between the app and this course. Map shows the app; ",{"t":"ui","text":"Learn"}," shows the course."],[{"t":"ui","text":"View"}," opens a menu that hides or shows each area of the screen. The next lesson shows how."],["The three certainty marks are explained at the end of this lesson."]]},{"t":"h","level":2,"id":"the-map","text":"The map"},{"t":"p","text":[{"t":"ui","text":"the map"}," is the big area in the middle. It is a map of Node's own source code, drawn as boxes inside boxes: your program at the top, the parts of Node below it."]},{"t":"p","text":["You move and zoom it like a street map. While a run plays, the boxes where work is happening light up."]},{"t":"h","level":2,"id":"the-code-panel","text":"The code panel"},{"t":"p","text":[{"t":"ui","text":"the code panel"}," shows your program. In the local app you can edit it, and ",{"t":"ui","text":"Run"}," starts it."]},{"t":"p","text":["You can also stop the program at a line you choose, and then let it go on one statement at a time, as in Chrome DevTools."]},{"t":"h","level":2,"id":"the-panels","text":"The panels"},{"t":"p","text":[{"t":"ui","text":"the panels"}," show the details of the moment you are looking at, in tabs: what is running, what is waiting to run, what the program printed, and more."]},{"t":"p","text":["Each lesson tells you which tab to open, so you can leave the rest closed."]},{"t":"h","level":2,"id":"the-playback-bar","text":"The playback bar"},{"t":"p","text":[{"t":"ui","text":"the playback bar"}," runs along the bottom. It plays a run back, fast or slowly. You can also step through a run, or jump to any moment of it."]},{"t":"p","text":["It works the same for a run you have just made and for a recording you have opened."]},{"t":"h","level":2,"id":"the-three-certainty-marks","text":"The three certainty marks"},{"t":"p","text":["Every fact on the screen says how nodejs-map knows it, with one of three marks:"]},{"t":"list","ordered":false,"items":[[{"t":"strong","text":"Observed"},": Node itself reported it."],[{"t":"strong","text":"Inferred"},": nodejs-map worked it out from what Node reported, following a written explanation that you can open."],[{"t":"strong","text":"Model"},": a drawing that explains how something works in general, rather than a measurement of your own run."]]},{"t":"p","text":[{"t":"ui","text":"the three certainty marks"}," in the top bar shows how each mark is drawn. Click them to read more. A later lesson, ",{"t":"link","text":"The three marks","href":"learn:three-marks"},", explains them in detail."]},{"t":"check","question":["You want to change one line of your program and run it again. Which area do you use, and which button?"],"answer":["The code panel. Edit the line there, then press Run."]}],"examples":{},"prev":{"id":"prerequisites","title":"What you need to know, and what you need installed"},"next":{"id":"hiding-areas","title":"Showing just the areas you need"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"what-it-is","chapter":"before","title":"What nodejs-map is","summary":"A tool that runs your Node.js program on your own computer and shows what happens inside Node while it runs.","blocks":[{"t":"p","text":["By the end of this lesson you can say what nodejs-map shows you and when it helps."]},{"t":"h","level":2,"id":"a-puzzle","text":"A puzzle"},{"t":"p","text":["Here is a tiny Node.js program:"]},{"t":"code","lang":"js","text":"console.log('A');\nsetTimeout(() => console.log('B'), 0);\nPromise.resolve().then(() => console.log('C'));\nconsole.log('D');"},{"t":"p","text":["It prints A, D, C, B — a different order from the one the lines are written in."]},{"t":"p","text":["Many developers who use Node every day cannot say exactly why. The answer is inside Node: in what Node does with your code after each line has run. nodejs-map is how you watch that happen."]},{"t":"h","level":2,"id":"what-nodejs-map-does","text":"What nodejs-map does"},{"t":"p","text":["nodejs-map runs your program on your own computer, with the Node.js you have installed. While the program runs, nodejs-map collects what Node reports about its own work."]},{"t":"p","text":["Then it shows you all of it:"]},{"t":"list","ordered":false,"items":[["your program, line by line;"],["what is running at each moment, and what is waiting to run later;"],["where in Node's own source code each piece of work happens, on a map you can zoom into like a street map."]]},{"t":"p","text":["For the puzzle above, you can watch \"B\" wait while \"C\" goes first, and see what made it wait."]},{"t":"h","level":2,"id":"recordings-and-replays","text":"Recordings and replays"},{"t":"p","text":["Most small programs finish in a few milliseconds — far too fast to watch as they go."]},{"t":"p","text":["So nodejs-map keeps a ",{"t":"strong","text":"recording"}," of every run. A recording is a list of everything Node reported during the run, in order, with the time of each report. It is data, not code."]},{"t":"p","text":["A ",{"t":"strong","text":"replay"}," plays a recording back, at a speed you choose. You can pause it, go one moment at a time, and jump back and forth, as many times as you like. Your program itself ran once; the replay shows you that run again."]},{"t":"h","level":2,"id":"two-ways-to-use-it","text":"Two ways to use it"},{"t":"list","ordered":false,"items":[["The ",{"t":"strong","text":"local app"},": you start it on your computer with ",{"t":"code","text":"npx nodejs-map"},". It opens in your browser, and it runs your own programs. The next lesson says what you need for it."],["The ",{"t":"strong","text":"player website"},": the same app as a public web page. It opens recordings — the ones that come with this course, and any that someone sends you. Handy on a borrowed computer or a phone."]]},{"t":"p","text":["When a lesson needs the local app, it says so."]},{"t":"h","level":2,"id":"when-it-helps","text":"When it helps"},{"t":"list","ordered":false,"items":[["To learn how Node works inside, from real runs instead of diagrams. This course does exactly that."],["To understand why your program prints things in a surprising order, or why a timer fires late."],["To find what holds up a server: which code runs so long that everything else has to wait."],["To share a run. Send a friend the recording and the same moments open on their screen, so you can both look at the very same run."]]},{"t":"h","level":2,"id":"good-to-know","text":"Good to know"},{"t":"list","ordered":false,"items":[["It works with the official Node.js you already have, using the reporting features built into it."],["It shows you the order of things and where in Node they happen, which is a different question from how much CPU time each of your own functions uses."],["It is at its best on one small program on your own computer, where it can watch every step closely."],["Some facts Node reports directly; others nodejs-map works out from those reports. The screen always tells you which is which, and a later lesson shows how."]]},{"t":"check","question":["A friend sends you a recording of their program. When you open it in nodejs-map, does their program run on your computer?"],"answer":["No. A recording is a list of what Node reported during their run. Opening it replays that list, so you see their run as it happened."]}],"examples":{},"next":{"id":"prerequisites","title":"What you need to know, and what you need installed"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"id":"what-uses-the-pool","chapter":"thread-pool","title":"What uses the thread pool","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.","blocks":[{"t":"p","text":["By the end of this lesson you can look at a Node API call and say whether it will occupy a thread pool thread."]},{"t":"h","level":2,"id":"four-kinds-of-pool-work","text":"Four kinds of pool work"},{"t":"example","example":"pool-users"},{"t":"p","text":["The program starts four requests and one timer. Open ",{"t":"ui","text":"Thread pool"}," and ",{"t":"ui","text":"Queues"},"."]},{"t":"list","ordered":false,"items":[[{"t":"code","text":"fs.stat"},": the file system. Almost every asynchronous ",{"t":"code","text":"fs"}," call uses the pool, because most operating systems have no portable non-blocking way to do file work."],[{"t":"code","text":"dns.lookup"},": asks the operating system's resolver (",{"t":"code","text":"getaddrinfo"},"), which blocks, so it runs on a pool thread."],[{"t":"code","text":"crypto.randomBytes"},", ",{"t":"code","text":"crypto.pbkdf2"}," and other heavy crypto calls with a callback."],[{"t":"code","text":"zlib.gzip"}," and the other zlib calls with a callback."],["The timer waits under Timers: libuv keeps time on the main thread, so timers need no pool thread."]]},{"t":"h","level":2,"id":"what-stays-on-the-main-thread","text":"What stays on the main thread"},{"t":"list","ordered":false,"items":[["Sockets: TCP, UDP, pipes and HTTP. The operating system tells libuv when a socket is ready, and libuv deals with it on the main thread. The networking chapter shows this."],["Timers, immediates, ticks and promise callbacks."],[{"t":"code","text":"dns.resolve"}," and friends: they talk to a DNS server over a socket, like any other network work."]]},{"t":"h","level":2,"id":"dns-lookup-and-an-ip-address","text":"dns.lookup and an IP address"},{"t":"example","example":"dns-lookup-thread-pool"},{"t":"p","text":[{"t":"code","text":"dns.lookup('localhost')"}," goes to the pool. ",{"t":"code","text":"dns.lookup('127.0.0.1')"}," stays on the main thread: an IP address is already the answer, so Node replies through ",{"t":"code","text":"process.nextTick"},", and that callback runs before anything else."]},{"t":"p","text":["To see the code behind it, open ",{"t":"ui","text":"Call paths"}," and choose ",{"t":"path","id":"p:dns-lookup","text":"dns.lookup(host, callback): getaddrinfo on the thread pool"},"."]},{"t":"note","kind":"honest","text":["On the official Node build, the work of pool threads is reported for crypto, zlib and the one-job ",{"t":"code","text":"fs.readFile"},". Other ",{"t":"code","text":"fs"}," requests and ",{"t":"code","text":"dns.lookup"}," are listed under \"Requests with the pool\", without a thread."]},{"t":"note","kind":"warn","text":[{"t":"code","text":"dns.lookup"}," may use at most about half of the pool's threads at once, so that slow name lookups cannot block all file work. Many slow lookups can still make each other wait."]},{"t":"check","question":["A server makes many outgoing HTTP requests to host names, and its file reads get slow. Which call is a likely cause, and why?"],"answer":["The ",{"t":"code","text":"dns.lookup"}," that ",{"t":"code","text":"http.get"}," does for each host name: every lookup takes a pool thread, and the file reads have to wait for a free one."]}],"examples":{"pool-users":{"id":"pool-users","title":"Who uses the thread pool","name":"pool-users.js","module":"commonjs","text":"// Who uses the thread pool? fs, dns.lookup, crypto and zlib do; a timer does not.\r\nconst fs = require('fs');\r\nconst dns = require('dns');\r\nconst crypto = require('crypto');\r\nconst zlib = require('zlib');\r\n\r\nconst done = [];\r\nfunction finished(name) {\r\n done.push(name);\r\n if (done.length === 4) console.log('pool work done: ' + done.sort().join(', '));\r\n}\r\n\r\nfs.stat(__filename, () => finished('fs.stat'));\r\ndns.lookup('localhost', () => finished('dns.lookup'));\r\ncrypto.randomBytes(16, () => finished('crypto.randomBytes'));\r\nzlib.gzip('hello', () => finished('zlib.gzip'));\r\nsetTimeout(() => {}, 1); // a timer: it waits in Timers, not in the pool\r\nconsole.log('script end: 4 jobs handed over');\r\n","racy":false,"output":["script end: 4 jobs handed over","pool work done: crypto.randomBytes, dns.lookup, fs.stat, zlib.gzip"],"recording":"rec/pool-users.nmrec.gz","steps":[{"index":48,"title":"Four requests for the pool","text":"The pool holds \"fs.stat\", \"dns.lookup\", \"crypto.randomBytes\" and \"zlib\" requests (see the Thread pool tab). The timer is under Timers: it never needs the pool."},{"index":112,"title":"All four are back","text":"All four callbacks have run. Pool threads were shown only for crypto and zlib: Node reports the work of pool threads for those jobs, not for fs.stat or dns.lookup."}]},"dns-lookup-thread-pool":{"id":"dns-lookup-thread-pool","title":"dns.lookup uses the thread pool","name":"dns-lookup.js","module":"commonjs","text":"// Shows: dns.lookup uses the operating system resolver (getaddrinfo) on the\n// thread pool, so its callback is always asynchronous. Deterministic.\n// Why: an IP literal needs no resolver call, and this case was observed to\n// call back before the thread pool lookup of \"localhost\" returns (see README:\n// verified by output on Node 26.13.1, not by reading lib/dns.js). Nothing\n// here uses the network: \"localhost\" is answered from the local hosts file.\n// Only the type of the address is printed, never its value (127.0.0.1 or ::1\n// depends on the system).\nconst dns = require('dns');\n\ndns.lookup('localhost', (err, address, family) => {\n console.log('lookup localhost callback: err=' + err + ' address is string=' + (typeof address === 'string'));\n});\ndns.lookup('127.0.0.1', (err, address, family) => {\n console.log('lookup 127.0.0.1 callback: address=' + address + ' family=' + family);\n});\nprocess.nextTick(() => console.log('nextTick'));\nconsole.log('sync: both lookups requested');\n","racy":false,"output":["sync: both lookups requested","lookup 127.0.0.1 callback: address=127.0.0.1 family=4","nextTick","lookup localhost callback: err=null address is string=true"],"recording":"rec/dns-lookup-thread-pool.nmrec.gz","steps":[{"index":18,"title":"localhost goes to the pool","text":"dns.lookup(\"localhost\") handed a request to the thread pool, the \"dns.lookup\" chip. A pool thread asks the operating system for the address (with its function getaddrinfo)."},{"index":21,"title":"An IP address skips the pool","text":"dns.lookup(\"127.0.0.1\") made no request to the pool: an IP address needs no lookup. Node added its callback to the nextTick queue instead: a \"nextTick\" chip."},{"index":31,"title":"Its callback runs first","text":"So the 127.0.0.1 callback runs in the round of ticks right after the script, even before the program's own tick, which was added after it."},{"index":47,"title":"localhost comes back from the pool","text":"The answer for localhost arrives on a turn of the loop (on Windows in the pending phase after poll; inferred). No thread is shown for this job, because Node reports nothing about pool threads for dns.lookup."}]}},"prev":{"id":"pool-size","title":"Changing the pool size"},"next":{"id":"blocking-the-loop","title":"Blocking the loop with CPU work"}}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|