Lesson 1: The Node runtime
Made for event-driven servers
Node.js was first released on 27 May 2009, and its original author was Ryan Dahl. In a talk at JSConf in Berlin in June 2018, Dahl said that he created and managed Node through its early development, and that his goal was heavily focused on programming event-driven HTTP servers. When Dahl left in 2012, Node had, by that account, more or less reached those goals.
Why it fits here: It answers this topic's question: Ryan Dahl made Node.js in 2009, aiming at event-driven HTTP servers.
Sources: Wikipedia: Node.js; Ryan Dahl: Design Mistakes in Node (JSConf EU 2018)
Topic: What Node is · history, people
Which version to run
Node's version numbers carry advice. Its release page says that up to Node.js 26, odd-numbered releases stopped being supported after six months, while even-numbered ones moved to Active LTS, long-term support, which typically means critical bugs are fixed for 30 months in all. From Node.js 27 the cycle is yearly, and every major version moves to LTS. Production apps should run only LTS releases.
Why it fits here: It adds to this topic's Node: production programs should run a long-term support release, kept fixed for about 30 months.
Source: Node.js: Previous releases
Topic: What Node is · numbers, standards
Restart on every save
Node can watch your files for you. Its manual says the option --watch starts Node in watch mode, where changes in the watched files make the process restart. By default it watches the entry file and every module it requires or imports. Added in Node 18.11.0, watch mode became stable in Node 22.0.0, so node --watch app.js reruns the program each time you save.
Why it fits here: It answers this topic's question: node --watch reruns a program whenever a watched file changes.
Source: Node.js manual: Command-line options
Topic: Running a program · tools, tricks
Check without running
A program can be checked for mistakes in its writing before it runs at all. The Node manual says the option -c, or --check, does a syntax check of the script without executing it. So node --check app.js reports a missing bracket or a misspelt keyword, with its line, and runs none of the program. It is handy before running a script that deletes or sends something.
Why it fits here: It adds a safety step to this topic's node app.js: node --check finds syntax errors without running anything.
Source: Node.js manual: Command-line options
Topic: Running a program · tools, mistakes
Sometimes at once, sometimes later
Writing to the screen is not always immediate. The Node manual says the writes behind console.log and console.error may be synchronous or not, depending on what they are connected to and the system. Writes to files are synchronous everywhere. Writes to a terminal are synchronous on POSIX systems such as Linux, but writes to a pipe there are asynchronous. The manual says the reasons are partly historical.
Why it fits here: It answers this topic's question: console.log's write is immediate to a terminal on Linux, but not into a pipe.
Source: Node.js manual: process (A note on process I/O)
Topic: Output: two streams · tools, standards
A stopwatch in the console
The console can time your code. The Node manual says console.time starts a timer, identified by a label, and console.timeEnd with the same label stops it and prints the elapsed time to standard output, in suitable units. Its example: if 3869 ms have passed, console.timeEnd shows 3.869s. So a slow part of a program can be measured with two lines.
Why it fits here: It adds a tool to this topic's console: console.time and console.timeEnd measure how long a piece of code takes.
Source: Node.js manual: console
Topic: Output: two streams · tools, tricks
.env without a package
Node can now read a .env file by itself. Its manual says the option --env-file loads environment variables from a file relative to the current folder, making them available in process.env. It was added in Node 20.6.0 and is no longer experimental since Node 24.10.0 and 22.21.0. So node --env-file=.env app.js works with no extra package, while the .env file stays out of git.
Why it fits here: It answers this topic's question: node --env-file=.env loads a .env file into process.env with no package.
Source: Node.js manual: Command-line options
Topic: What a program is given: process · tools, tricks
Everything in process.env is text
process.env keeps only strings. The Node manual says that assigning a property on process.env converts the value to a string, so env.test = null stores the text null, not an empty value. It calls this behaviour deprecated, and warns that future versions may throw an error for values that are not a string, a number or a boolean.
Why it fits here: It sharpens this topic's process.env: every value in it is a string, as Node turns anything stored there into text.
Source: Node.js manual: process
Topic: What a program is given: process · tools, mistakes
process.exit can cut output short
process.exit does not wait politely. The Node manual says calling it forces the process to exit as quickly as possible, even if asynchronous work is still pending, including writes to standard output and standard error. It adds that in most situations there is no need to call process.exit at all: the process ends by itself when no work is left, and process.exitCode can set the code.
Why it fits here: It answers this topic's question: process.exit can end the program before pending output is written, so process.exitCode is safer.
Source: Node.js manual: process
Topic: Ending with an exit code · tools, mistakes
Last words must be quick
A program can run code as it exits, but only quick code. The Node manual says listeners on the exit event must only do synchronous work. The process exits straight after calling them, and any work still queued in the event loop is abandoned. A timer started in an exit listener therefore never fires.
Why it fits here: It adds a rule to this topic's ending: code that runs on exit must be synchronous, as nothing queued runs afterwards.
Source: Node.js manual: process
Topic: Ending with an exit code · tools, standards
libuv, the loop under Node
Node's event loop comes from a library of its own. The libuv documentation calls it a multi-platform support library with a focus on asynchronous input and output, primarily developed for use by Node.js. Other projects use it too, such as the language Julia and uvloop for Python. So the loop that runs Node's callbacks is libuv's.
Why it fits here: It names the machinery behind this topic's event loop: libuv, a library made for Node.js.
Source: libuv documentation
Topic: One engine, one job at a time: the event loop · tools, history
Four threads behind the scenes
Your JavaScript runs on one thread, but Node is not only one thread. The libuv documentation says it keeps a thread pool for work such as file system operations, with a default size of 4 threads, changeable at startup with UV_THREADPOOL_SIZE up to 1024. The Node manual adds that all fs APIs other than file watchers, and some crypto APIs, use that pool.
Why it fits here: It answers this topic's question: JavaScript runs on one thread, while file work goes to libuv's pool of 4 threads.
Sources: libuv documentation: Thread pool work scheduling; Node.js manual: Command-line options
Topic: One engine, one job at a time: the event loop · numbers, tools
Lesson 2: Modules
Every file sits inside a function
Node keeps a file's names private with a trick. Its manual says that before a module's code runs, Node wraps it in a function with five parameters: exports, require, module, __filename and __dirname. Because the code runs inside that function, its top-level variables stay local to the module instead of becoming global. It is also where require and module come from.
Why it fits here: It answers this topic's question: Node wraps each file in a function, so its names stay inside.
Source: Node.js manual: Modules (CommonJS)
Topic: Why programs are built from parts · tools, standards
Node's own modules are files too
The modules that come with Node are built the same way as yours. The Node manual says these built-in modules are compiled into the program, and are defined in Node's source, in its lib/ folder. Each page of the manual names its file: the page for fs begins with Source Code: lib/fs.js. Reading such a file shows how a large module is split into parts.
Why it fits here: It shows this topic's idea at full size: Node's own built-in modules are files in its lib/ folder.
Sources: Node.js manual: Modules (CommonJS); Node.js manual: File system
Topic: Why programs are built from parts · tools, history
Half-finished exports
Two modules may require each other, and then one sees the other half done. The Node manual says that with circular require calls, a module might not have finished running when it is returned. In its example, a.js requires b.js, and b.js requires a.js back: b.js then receives an unfinished copy of a.js's exports, with only what a.js had set so far.
Why it fits here: It answers this topic's question: in a circle of requires, one module gets the other's exports half finished.
Source: Node.js manual: Modules (CommonJS)
Topic: Loading a module: require · tools, mistakes
Reloading from the cache
The cache behind require is an object you can reach. The Node manual says modules are cached in require.cache when they are required, and that deleting a key from it makes the next require load the module afresh. That does not apply to native addons, for which reloading gives an error. Tools that reload code while it runs work this way.
Why it fits here: It adds to this topic's run-once rule: deleting a module's entry in require.cache makes the next require run it again.
Source: Node.js manual: Modules (CommonJS)
Topic: Loading a module: require · tools, tricks
Too late in a timer
What a module offers must be settled straight away. The Node manual says assignment to module.exports must be done immediately, and cannot be done in any callbacks. Its example sets module.exports inside a timer of 0 milliseconds; the file that requires it has already received the old exports, so its value a is undefined.
Why it fits here: It answers this topic's question: module.exports must be set at once, as a timer would set it after require has returned.
Source: Node.js manual: Modules (CommonJS)
Topic: What a module offers: module.exports and exports · tools, mistakes
A module that offers a class
A module can offer a single class instead of an object. Node's own events module does: its manual says all objects that emit events are instances of the EventEmitter class, and its examples load that class with const EventEmitter = require('node:events'). What comes back is the class itself, ready for new or for extends, because the class is what module.exports holds.
Why it fits here: It shows this topic's any-value rule in Node itself: require('node:events') gives back the EventEmitter class.
Source: Node.js manual: Events
Topic: What a module offers: module.exports and exports · tools, standards
Modules only with node:
Some built-in modules answer only to the node: prefix. The Node manual says that a built-in name with node: always gives the built-in module, and bypasses the require cache. It lists the modules that require the prefix: node:ffi, node:sea, node:sqlite, node:test and node:test/reporters. So require('node:test') loads Node's test runner, while a bare require('test') looks for a package of that name.
Why it fits here: It answers this topic's question: modules such as node:test and node:sqlite can only be loaded with the node: prefix.
Source: Node.js manual: Modules (CommonJS)
Topic: How require finds a module · tools, standards
A fourth ending: .node
require's list of endings has one more after .js and .json. The Node manual's step-by-step search says that if X.node is a file, it is loaded as a binary addon. Such addons are compiled code, often written in C or C++, that Node loads like any module. That is how some packages reach speeds or system features that JavaScript alone cannot.
Why it fits here: It completes this topic's search order: after .js and .json, require also tries .node, a compiled binary addon.
Sources: Node.js manual: Modules (CommonJS); Node.js manual: C++ addons
Topic: How require finds a module · tools, languages
TypeScript, with the types wiped out
Node can now run TypeScript files itself. Its manual says that by default Node executes TypeScript files that contain only erasable TypeScript syntax: it replaces that syntax with whitespace, and performs no type checking. Type stripping was added in Node 22.6.0, became the default in 23.6.0 and 22.18.0, and became stable in 25.2.0 and 24.12.0.
Why it fits here: It answers this topic's question: Node runs simple TypeScript files directly, by wiping out the types, though it checks none of them.
Source: Node.js manual: Modules: TypeScript
Topic: ES modules in Node: import and export · tools, languages
Node can guess the module kind
A .js file with no type field need not fail when it uses import. The Node manual describes syntax detection: Node inspects the source of an ambiguous file to see whether it holds ES module syntax, and if it does, treats it as an ES module. Added in Node 21.1.0 and 20.10.0, it has been on by default since 22.7.0 and 20.19.0. Setting the type field is still clearer.
Why it fits here: It adds to this topic's type field: Node can detect import and export in an ambiguous .js file and load it as an ES module.
Source: Node.js manual: Modules: Packages
Topic: ES modules in Node: import and export · tools, standards
require can load ES modules now
The wall between the two kinds is lower than it was. The Node manual says require() can load ES modules, a feature added in Node 22.0.0 and 20.17.0. It stopped printing an experimental warning by default in 23.5.0, 22.13.0 and 20.19.0, and is no longer experimental since 25.4.0. So a CommonJS file can often require an ES module directly, without import().
Why it fits here: It answers this topic's question: recent versions of Node let require load an ES module directly.
Source: Node.js manual: Modules (CommonJS)
Topic: Choosing, and mixing the two · tools, history
require inside an ES module
An ES module has no require of its own, but it can make one. The Node manual describes createRequire in the node:module module, added in Node 12.2.0. Its example imports createRequire, then writes const require = createRequire(import.meta.url), and uses that require to load a CommonJS file next to it.
Why it fits here: It adds the other direction to this topic's mixing: createRequire gives an ES module a require of its own.
Source: Node.js manual: Modules: node:module API
Topic: Choosing, and mixing the two · tools, tricks
Lesson 3: npm and packages
npm, also known as Isaac
npm's original author was Isaac Z. Schlueter, and its first release came on 12 January 2010. In a talk in 2018, Ryan Dahl, who created Node, gave npm much of the credit for Node's growth after he left. One slide says npm, also known as Isaac, decoupled the core Node library and allowed the ecosystem to be distributed: anyone could share a package without changing Node itself.
Why it fits here: It answers this topic's question: Isaac Z. Schlueter started npm in 2010, and Ryan Dahl credited it with spreading Node's ecosystem.
Sources: Wikipedia: npm; Ryan Dahl: Design Mistakes in Node (JSConf EU 2018)
Topic: Packages and npm · history, people
npm joined GitHub in 2020
The registry has had a change of owner. On 16 March 2020, Nat Friedman, then GitHub's chief executive, announced that GitHub had signed an agreement to acquire npm, calling it a critical part of the JavaScript world. Wikipedia now lists npm, Inc. as a subsidiary of GitHub, which is itself a subsidiary of Microsoft.
Why it fits here: It completes this topic's npm: since 2020 the registry belongs to GitHub, and so to Microsoft.
Sources: GitHub Blog: npm is joining GitHub; Wikipedia: npm
Topic: Packages and npm · history, internet
214 characters, all small letters
A package name has rules. npm's documentation for package.json says a name must be 214 characters or fewer, the scope included, and that new packages must not have capital letters in their names. The reason it gives: the name becomes part of a web address, an argument on the command line and a folder name, so it cannot hold characters that are unsafe in addresses.
Why it fits here: It answers this topic's question: a package name has at most 214 characters and no capital letters.
Source: npm Docs: package.json
Topic: The project's card: package.json · standards, numbers
A field that stops publishing
One field protects a project from being shared by accident. npm's documentation says that if package.json holds "private": true, npm will refuse to publish it. It calls this a way to prevent the accidental publication of private repositories. Most app projects, as opposed to libraries meant for others, set it at once.
Why it fits here: It adds a safety field to this topic's package.json: "private": true makes npm refuse to publish the project.
Source: npm Docs: package.json
Topic: The project's card: package.json · tools, mistakes
node_modules/.bin joins the PATH
Scripts can name tools that are installed only in your project. npm's documentation says that in addition to the shell's existing PATH, npm run adds node_modules/.bin to the PATH given to scripts. So a tool that a dependency installs there can be called by its bare name inside a script, without writing node_modules/.bin in front.
Why it fits here: It answers this topic's question: npm run puts node_modules/.bin on the PATH, so scripts can call local tools by name.
Source: npm Docs: npm run
Topic: A project's jobs: scripts · tools, tricks
Scripts that run before and after
A script can have helpers that run around it. npm's documentation says that adding pre or post to the front of a script's name makes another script that runs before or after it. Its example has precompress, compress and postcompress: npm run compress then runs all three, in that order.
Why it fits here: It adds to this topic's scripts: a pre or post script runs by itself before or after the script of the same name.
Source: npm Docs: Scripts
Topic: A project's jobs: scripts · tools, tricks
The day left-pad vanished
In March 2016 a dispute over a package name broke many builds at once. npm's own account says that an author unpublished the package kik and 272 other packages without warning, and one of them was left-pad. Shortly after 2:30 in the afternoon, Pacific time, on Tuesday 22 March, npm saw hundreds of failures per minute, and many thousands of projects were affected.
Why it fits here: It answers this topic's question: when left-pad was unpublished in 2016, many thousands of projects that depended on it failed to install.
Source: npm Blog: kik, left-pad, and npm
Topic: Installing a package: npm install · history, mistakes
npm ci, the strict install
npm has a stricter install for machines that build and test code. Its documentation says npm ci is meant for automated places such as test platforms, continuous integration and deployment. If the lock file and package.json disagree, npm ci stops with an error instead of updating the lock. It removes any existing node_modules first, and never writes to package.json or the lock: installs are frozen.
Why it fits here: It adds to this topic's lock file: npm ci installs exactly what the lock says, or stops.
Source: npm Docs: npm ci
Topic: Installing a package: npm install · tools, standards
Why the caret appears
npm writes the caret for you. Its documentation says the setting save-prefix, whose default is ^, decides how a version installed into package.json is written. So installing version 1.2.3 records ^1.2.3, which allows minor upgrades. After npm config set save-prefix='~', the same install records ~1.2.3, which allows only patch upgrades.
Why it fits here: It answers this topic's question: npm's save-prefix setting, ^ by default, puts the caret in front.
Source: npm Docs: Config
Topic: Versions and ranges · tools, standards
x, X and * as wild cards
Ranges can also be written with wild cards. npm's semver documentation describes X-ranges, where x, X or * stands in for one of the three numbers. So 1.2.x accepts any patch of 1.2, and 1.x means at least 1.0.0 but below 2.0.0. A lone * accepts any version that is not a pre-release, which is rarely a wise choice for a real project.
Why it fits here: It adds to this topic's ranges: 1.2.x and 1.x are wild-card ranges, and * accepts almost any version.
Source: npm: node-semver
Topic: Versions and ranges · standards, tricks
Global packages are not for require
A package installed with npm install -g is not where require looks. npm's documentation says global installs on Unix go to the prefix folder's lib/node_modules. The Node manual explains that require searches global folders only through the NODE_PATH setting and a few old folders, which it calls mostly historic. It strongly encourages dependencies in the local node_modules, which load faster and more reliably.
Why it fits here: It answers this topic's question: require does not search npm's global folder, so dependencies belong in the local node_modules.
Sources: npm Docs: Folders; Node.js manual: Modules (CommonJS)
Topic: How Node finds a package · tools, mistakes
NODE_PATH, a PATH for modules
Node has a setting that works like the shell's PATH, but for modules. The Node manual says that if NODE_PATH holds a list of absolute paths, separated by colons, Node searches them for modules it has not found elsewhere. On Windows the list is separated by semicolons. Like PATH, it is read from the environment, so it can be set for one command.
Why it fits here: It links this topic's search to the Linux track's PATH: NODE_PATH is a colon-separated list of extra folders for modules.
Source: Node.js manual: Modules (CommonJS)
Topic: How Node finds a package · tools, standards
Lesson 4: Files
A write that will not overwrite
A write can be told never to replace an existing file. The Node manual lists file system flags, given as the flag option: w opens a file for writing and empties it if it exists, while wx is like w but fails if the path exists. So fs.writeFileSync(name, text, { flag: "wx" }) makes a new file, or throws an error instead of wiping out an old one.
Why it fits here: It answers this topic's question: the flag wx makes writeFileSync fail rather than replace an existing file.
Source: Node.js manual: File system (flags)
Topic: Reading and writing a file · tools, tricks
Two kinds of line ending
A newline is not the same everywhere. The Node manual says os.EOL holds the operating system's own end-of-line marker: a single \n on POSIX systems such as Linux, and the pair \r\n on Windows. A file written on one system can therefore show odd line endings on the other, and os.EOL lets a program write the local kind.
Why it fits here: It adds to this topic's newlines: Linux ends a line with \n and Windows with \r\n, and os.EOL holds the local one.
Source: Node.js manual: OS
Topic: Reading and writing a file · tools, standards
A Buffer is a Uint8Array
Buffer is not a stranger to JavaScript. The Node manual says the Buffer class is a subclass of JavaScript's own Uint8Array, a typed array of 8-bit numbers, extended with extra methods. Node's functions accept a plain Uint8Array wherever they accept a Buffer. So what you learn about typed arrays in the browser also works on the bytes of a file.
Why it fits here: It places this topic's Buffer in the language: it is JavaScript's Uint8Array with extra methods.
Source: Node.js manual: Buffer
Topic: Text and bytes: Buffers · tools, standards
allocUnsafe can show old memory
Buffer.allocUnsafe lives up to its name. The Node manual says the memory behind a Buffer made this way is not initialized, so its contents are unknown and may contain sensitive data left over in memory. It points to Buffer.alloc instead, which fills a new Buffer with zeroes. allocUnsafe is faster, and safe only when every byte is written before it is read.
Why it fits here: It answers this topic's question: Buffer.allocUnsafe may hold leftover data, while Buffer.alloc starts with zeroes.
Source: Node.js manual: Buffer
Topic: Text and bytes: Buffers · tools, mistakes
Indents stop at 10
The number in JSON.stringify(data, null, 2) has a ceiling. MDN explains that this third argument, when it is a number, gives the number of spaces to indent with, clamped to 10: any number above 10 is treated as 10. A value below 1 means no indentation at all, and the whole text comes out on one line.
Why it fits here: It sharpens this topic's JSON.stringify: its indent is at most 10 spaces, and below 1 there is none.
Sources: MDN: JSON.stringify(); ECMAScript Language Specification: JSON.stringify
Topic: Data in files: JSON · tools, numbers
Write to a copy, then rename
A program that stops halfway through writeFileSync can leave a broken JSON file. A safer habit writes the new text to a temporary file first, then renames it over the old one. The Linux manual for rename says that if the new name already exists, it is replaced atomically: no other program will ever find the file missing. Readers see the old file or the new one, never half of one.
Why it fits here: It answers this topic's question: writing to a temporary file and renaming it means no reader ever sees a half-written JSON file.
Source: Linux man-pages: rename(2)
Topic: Data in files: JSON · tools, tricks
cp -r in one call
Copying a whole folder needs no loop of your own. The Node manual describes fs.cpSync, added in Node 16.7.0 and no longer experimental since 22.3.0. It copies the entire directory structure from one place to another, subfolders and files included, and with a folder it behaves like cp dir1/ dir2/ in the shell.
Why it fits here: It answers this topic's question: fs.cpSync copies a folder and everything inside it, like cp -r.
Source: Node.js manual: File system
Topic: Folders: make, list, look, move, remove · tools, tricks
A folder with a random name
Programs often need a scratch folder that clashes with nothing. The Node manual describes fs.mkdtemp, which creates a unique temporary folder. It adds six random characters behind a prefix you give, so mkdtempSync('/tmp/shop-') might make /tmp/shop-a1b2c3. The manual warns that some systems, notably the BSDs, can add more than six.
Why it fits here: It adds to this topic's mkdirSync: mkdtemp makes a folder with a unique random name for scratch work.
Source: Node.js manual: File system
Topic: Folders: make, list, look, move, remove · tools, numbers
ENOENT, no entity
The odd name ENOENT has a meaning. Node's manual of errors says ENOENT, no such file or directory, is commonly raised by fs operations when part of a path does not exist, and explains it as no entity, file or directory, found by the given path. So E-NO-ENT reads as error, no entity: nothing is there.
Why it fits here: It answers this topic's question: ENOENT reads as error, no entity, meaning nothing exists at that path.
Source: Node.js manual: Errors (Common system errors)
Topic: When it goes wrong: Node's errors · words, tools
Too many open files
A program can run out of file handles. Node's manual of errors describes EMFILE, too many open files: the limit of file descriptors has been reached, and no more can be opened until one is closed. It says this happens when opening many files at once, especially on macOS with its low limit, and suggests raising it with ulimit -n 2048 in the shell that runs Node.
Why it fits here: It adds a code to this topic's list: EMFILE means too many files are open at once, and ulimit -n raises the limit.
Source: Node.js manual: Errors (Common system errors)
Topic: When it goes wrong: Node's errors · tools, numbers
Not Sync in a server
The Sync forms are fine in a script, but Node's own guide warns against them in a server. Its page Don't Block the Event Loop lists the file system among the core modules with expensive synchronous APIs, and says plainly: do not use the synchronous file system APIs. On a network drive such as NFS, it notes, access times can vary widely, and every waiting request would wait too.
Why it fits here: It answers this topic's question: Node's guide says not to use the Sync file functions in a server.
Source: Node.js: Don't Block the Event Loop
Topic: Three ways to ask: sync, callback, promise · tools, standards
Promises came in Node 10
The promise form is younger than the other two. The Node manual says the promises API was added in Node 10.0.0, at first reachable only as require('fs').promises. It stopped being experimental in 11.14.0 and 10.17.0, and became the module fs/promises in Node 14.0.0. Under the surface, it runs file work on Node's thread pool, off the event loop.
Why it fits here: It dates this topic's third form: fs/promises arrived in Node 10 and became its own module in Node 14.
Source: Node.js manual: File system (Promises API)
Topic: Three ways to ask: sync, callback, promise · history, tools
One module, two kinds of path
The path module follows the system it runs on. The Node manual says that on Windows it assumes Windows-style paths, with backslashes. Its example: path.basename('C:\\temp\\myfile.html') gives myfile.html on Windows, but the whole string back on POSIX, where a backslash is not a separator. path.posix and path.win32 force one style on any system.
Why it fits here: It answers this topic's question: path follows the running system, so basename can differ between Windows and Linux.
Source: Node.js manual: Path (Windows vs. POSIX)
Topic: Paths: finding files from anywhere · tools, standards
From a file URL to a path
ES modules name their own file as a URL, not a path. The Node manual describes url.fileURLToPath, added in Node 10.12.0, which turns a file: URL into an ordinary path. It decodes characters written as percent codes and makes sure the result is a valid absolute path on any system. So fileURLToPath(import.meta.url) gives the module's own path.
Why it fits here: It adds to this topic's paths: fileURLToPath turns an ES module's file URL into a path that fs can use.
Source: Node.js manual: URL
Topic: Paths: finding files from anywhere · tools, standards
Lesson 5: Events and streams
A warning at 11 listeners
Node watches for listeners piling up. Its manual says that by default an EventEmitter prints a warning if more than 10 listeners are added for one event, a useful default that helps find memory leaks. The method setMaxListeners changes the limit for one emitter, and Infinity or 0 removes it. A program that adds a listener on every request, and never removes one, trips the warning quickly.
Why it fits here: It answers this topic's question: Node warns when more than 10 listeners pile up on one event, as that often means a leak.
Source: Node.js manual: Events
Topic: Events, listeners and emit · tools, numbers
An older name for emitters
The idea behind EventEmitter is older than Node. Software designers call it the observer pattern: an object, the subject, keeps a list of its observers and tells them of every change, often by calling one of their methods. It is one of the 23 patterns of the 1994 book Design Patterns, by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, called the Gang of Four.
Why it fits here: It names this topic's idea: an emitter and its listeners are the observer pattern, from the 1994 book Design Patterns.
Sources: Wikipedia: Observer pattern; Wikipedia: Design Patterns; Refactoring.Guru: Observer
Topic: Events, listeners and emit · history, standards
Events as a loop
Waiting for one event has a big brother: waiting for every one. The Node manual says events.on returns an async iterator of an event, so for await (const args of on(emitter, "ring")) runs once for each ring, with the arguments as an array. It throws if the emitter emits error, and removes its listeners when the loop is left.
Why it fits here: It answers this topic's question: events.on turns an event into a loop that for await can wait on, ring after ring.
Source: Node.js manual: Events
Topic: Listening once, in order, and no more · tools, tricks
An event about listeners
An emitter even announces its own listeners. The Node manual says an EventEmitter emits its own newListener event before a listener is added to its list. Listeners for newListener receive the event's name and the listener being added. So a program can notice the first listener for an event, and start some work only when someone is listening.
Why it fits here: It adds to this topic's listeners: an emitter rings newListener whenever a listener is added.
Source: Node.js manual: Events
Topic: Listening once, in order, and no more · tools, standards
A switch for async listeners
An async listener that throws leaves a rejected promise that nobody handles. Node has a switch for that. Its manual calls async event handlers problematic for this reason, and offers the option captureRejections. An emitter made with new EventEmitter({ captureRejections: true }) catches such a rejection and routes the error to its error event, where a listener can deal with it.
Why it fits here: It answers this topic's question: with captureRejections, an emitter sends an async listener's error to its error event.
Source: Node.js manual: Events
Topic: The error event · tools, mistakes
Watching errors without catching them
Some code only wants to see errors, for a log, without handling them. The Node manual offers events.errorMonitor for that. A listener added with it is called before the regular error listeners, but changes nothing about what happens next: the program still crashes if no regular error listener is installed.
Why it fits here: It sharpens this topic's rule: an errorMonitor listener only watches, so a real error listener is still needed.
Source: Node.js manual: Events
Topic: The error event · tools, standards
The browser's EventTarget, in Node
Node also speaks the browser's language of events. Its manual says Node has its own implementation of the EventTarget web API, with addEventListener, used by some of Node's core APIs. Since Node 15.0.0, EventTarget and Event are available everywhere as globals, so code written for the browser's events can often run in Node unchanged.
Why it fits here: It answers this topic's question: Node offers the browser's EventTarget as well as its own EventEmitter.
Source: Node.js manual: Events (EventTarget and Event API)
Topic: Emitters of your own · tools, standards
Before class there was util.inherits
Emitters of your own were once made without class. Older Node code used util.inherits to copy EventEmitter's methods onto a constructor function. Node's manual now says its use is discouraged, and asks for the ES6 class and extends keywords instead, adding that the two styles are semantically incompatible. So in old code, util.inherits is a sign of the older style.
Why it fits here: It dates this topic's class ... extends EventEmitter: older Node code used util.inherits, now discouraged.
Source: Node.js manual: Util
Topic: Emitters of your own · history, tools
Streams once poured at once
Node's streams were not always this patient. Its manual says that before Node 0.10, data events began at once, instead of waiting to be asked, so a program that needed time to decide what to do had to store the data or lose it. Today every readable stream begins paused, and starts to flow when asked, for example when a data listener is added.
Why it fits here: It answers this topic's question: before Node 0.10 data poured out at once, while today a stream waits until something asks.
Source: Node.js manual: Stream (Compatibility with older Node.js versions)
Topic: Streams: a file a piece at a time · history, tools
readline also listens to people
readline is not only for files. Its manual says it reads any readable stream one line at a time, such as process.stdin, where typed input arrives. In a terminal it keeps a history of up to 30 typed lines by default, and Ctrl+P brings back the previous one. Given a completer function, it also completes a word when Tab is pressed.
Why it fits here: It widens this topic's readline: besides a file's lines, it serves people typing, with a history and Tab completion.
Source: Node.js manual: Readline
Topic: Streams: a file a piece at a time · tools, numbers
pipe leaves a mess on errors
pipe has a weak spot. The Node manual warns that if the readable stream emits an error during processing, the writable destination is not closed automatically, so each stream must be closed by hand to prevent memory leaks. Its answer is stream.pipeline, which pipes between streams while forwarding errors, cleaning up properly and calling back when the pipeline is complete.
Why it fits here: It answers this topic's question: pipe does not close the writer when the reader fails, while stream.pipeline cleans up both.
Source: Node.js manual: Stream
Topic: Writing streams and pipes · tools, mistakes
Streams of objects
A stream can carry more than bytes. Node's manual says the streams made by Node's own APIs carry only strings and binary data, such as buffers, while a stream made with the objectMode option can carry other JavaScript values. The one value it cannot carry is null, which a stream uses to signal its end. In object mode, highWaterMark counts objects, not bytes.
Why it fits here: It widens this topic's chunks: a stream made with objectMode takes any value but null, and its highWaterMark counts objects.
Source: Node.js manual: Stream (Object mode)
Topic: Writing streams and pipes · tools, standards
Lesson 6: An HTTP server
Doors below 1024 are guarded
On Linux, the low ports are guarded. The Linux manual page for IP says that port numbers below 1024 are called privileged ports, and that only a privileged process may bind to them, such as one with the capability CAP_NET_BIND_SERVICE. So an ordinary program cannot open port 80 without extra permission, while port 3000 needs none.
Why it fits here: It answers this topic's question: on Linux, ports below 1024 need special permission, so port 3000 is free to use.
Source: Linux manual page: ip(7)
Topic: Requests and responses · tools, numbers
Sixteen million names for this computer
The address 127.0.0.1 is one of many. The internet's standards reserve every address that begins with 127, more than 16 million of them, for loopback: a packet sent to any of them comes back to the same computer. The host requirements standard, RFC 1122 of October 1989, says that such an address must never appear outside a host.
Why it fits here: It widens this topic's localhost: every address that begins with 127, not only 127.0.0.1, means this same computer.
Sources: Wikipedia: Localhost; RFC 1122: Requirements for Internet Hosts
Topic: Requests and responses · numbers, standards
Port 0 means any free port
A server can let the computer choose its door. Node's manual says that if listen is given port 0, or no port at all, the operating system picks an arbitrary unused port, and server.address().port reports it once the server is listening. Two servers started this way get two different ports, so they never fight over one.
Why it fits here: It answers this topic's question: listen(0) asks the system for any free port, and server.address().port tells which.
Source: Node.js manual: Net
Topic: A first server · tools, tricks
Five minutes to ask
A server does not wait for ever. Since Node 18.0.0, its manual says, a server gives each client 3,00,000 milliseconds, five minutes, to send its whole request; after that it answers 408 and closes the connection. Before 18.0.0 there was no limit. The manual says the limit must stay above 0 to protect against denial-of-service attacks when no other server stands in front.
Why it fits here: It adds to this topic's server: since Node 18.0.0, a client has five minutes to send a request, or gets 408.
Source: Node.js manual: HTTP (server.requestTimeout)
Topic: A first server · numbers, history
Browsers guess a missing type
An answer without Content-Type leaves the client to guess. MDN says that when there is no type, browsers may perform MIME sniffing: guessing the type by looking at the bytes, each browser in its own way. A server that wants its types obeyed sends X-Content-Type-Options: nosniff, which says that the types in its Content-Type headers should be respected and not changed.
Why it fits here: It answers this topic's question: a browser guesses a missing type from the bytes, which nosniff tells it not to do.
Sources: MDN: MIME types; MDN: X-Content-Type-Options; WHATWG Fetch Standard: X-Content-Type-Options; WHATWG MIME Sniffing Standard
Topic: Writing the response · standards, mistakes
Five seconds of keep-alive
Node keeps a connection open after an answer, ready for the next request, but not for long. Its manual says that by default a server waits 5 seconds, 5000 milliseconds, for more data after it finishes the last response, and then destroys the socket. Node 24.6.0 and 22.19.0 added a buffer of 1 second more, to reduce connection reset errors.
Why it fits here: It adds to this topic's keep-alive header: Node keeps an idle connection open for 5 seconds by default, plus a 1-second buffer.
Source: Node.js manual: HTTP (server.keepAliveTimeout)
Topic: Writing the response · numbers, tools
Capital letters count in paths
Two addresses can differ only in capitals. The URI standard, RFC 3986, says that the scheme and the host are case-insensitive, so HTTP://www.EXAMPLE.com/ and http://www.example.com/ are the same. The other parts, the path among them, are case-sensitive unless a scheme says otherwise. So a route for /gauges does not answer /Gauges unless the server is written to.
Why it fits here: It answers this topic's question: /Gauges and /gauges are different paths, though the host's capitals do not matter.
Source: RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
Topic: Routes: one server, many answers · standards, mistakes
Gone, not just missing
HTTP has a stronger word than 404. The HTTP standard, RFC 9110, says that 410 Gone means the resource is no longer available and that this is likely to be permanent, so that links to it should be removed. It adds that a server that does not know whether the loss is permanent ought to use 404 Not Found instead.
Why it fits here: It adds to this topic's 404: 410 Gone says a path is gone for good, while 404 makes no such promise.
Source: RFC 9110: HTTP Semantics
Topic: Routes: one server, many answers · standards, tools
Asking before sending
A client with a big body can ask first. It sends the header Expect: 100-continue and waits. The curl book says curl does this by default for a POST known or suspected to be larger than one megabyte, and sends the body once the server answers 100. Node's manual says a server that does not listen for checkContinue answers 100 Continue as appropriate.
Why it fits here: It answers this topic's question: Expect: 100-continue lets a client ask before it sends a big body, and Node says yes by default.
Sources: Everything curl: Expect 100-continue; Node.js manual: HTTP (Event: 'checkContinue')
Topic: Bodies: data sent to the server · tools, standards
Undici, which means eleven
Node's fetch has a name of its own underneath. The Node manual says its fetch is based on undici, an HTTP/1.1 client written from scratch for Node.js, and process.versions.undici gives the version inside. The project's own page explains the name: undici means eleven in Italian, from HTTP/1.1, and it is also a Stranger Things reference.
Why it fits here: It adds to this topic's fetch: Node's fetch runs on undici, an HTTP/1.1 client named after the Italian for eleven.
Sources: Node.js manual: Globals (fetch); undici on GitHub (README)
Topic: Bodies: data sent to the server · history, tools
No fact matches. Try a shorter word, or take the tag off.