Glossary
111 terms from Node.js Basics, in plain words, each with the chapter that teaches it.
#
- .env file
- A file of `NAME=value` settings that Node loads with `--env-file=.env`. Keep it out of Git because it can hold secrets, and commit `.env.example` to list the names for others.
- /dev/null
- A special file on macOS and Linux that throws away anything written to it. Adding `2>/dev/null` hides a command's stderr, which shows the logger writes there.
- 2> (redirect stderr)
- In the terminal, `>` sends a program's stdout to a file and `2>` sends its stderr to a file. For example, `node stock-report.js > report.txt` puts the table in the file while error messages still show on screen.
A
- AbortSignal.timeout
- Creates a signal that cancels a `fetch` after a set time, such as `AbortSignal.timeout(5000)` for 5 seconds. It stops a request from hanging forever when the server doesn't answer.
- Absolute path / relative path
- An absolute path starts from the top of the disk, like `/home/jo/kc-stock/data/inventory.json`. A relative path, like `data/inventory.json`, starts from the folder the program was run from.
- API (application programming interface)
- A server that programs talk to over HTTP, like Kettle & Crane's order API. A JSON API sends and receives its data as JSON.
- Append
- Adding to the end of a file instead of replacing its contents. `appendFile` does it, and the `flags: "a"` option makes a log stream add to the file on each run.
- assert (node:assert/strict)
- Node's built-in checking functions for tests. Each one throws an `AssertionError` when its check is false, which fails the test: `equal` compares with `===`, `deepEqual` compares contents, and `throws` and `rejects` check for errors.
- Atomic write
- Saving a file by writing a temporary `.tmp` file and then renaming it over the original. The real file is always a complete old or new version, never half-written after a crash.
B
- Backpressure
- When a slow writable stream tells a fast readable stream to pause until it catches up. `pipeline` handles this for you.
- Bearer token
- A secret string sent in the `Authorization` header as `Bearer <token>` to prove who is calling an API. Anyone who holds it gets in, so Kettle & Crane keeps it in `KC_API_TOKEN`.
- Blocking the event loop
- Running a long calculation so Node can't run anything else, not even timers, until it ends. Waiting for I/O is fine, but long loops are not.
- Body
- The data part of an HTTP request or response. A POST sends its body as a JSON string, and `res.json()` reads the response body.
- Breakpoint
- A marked line, set in VS Code by clicking left of the line number, where the debugger pauses the program so you can inspect variables. Writing `debugger;` in code does the same.
- Buffer
- Raw bytes. A file stream without an encoding gives chunks as Buffers, and `toString()` turns them into text.
- Built-in module
- A module that ships with Node, so nothing needs installing. You import it with the `node:` prefix, such as `node:fs`.
C
- Child process
- A separate program that your Node program starts and waits for. `execFile` from `node:child_process` runs one and returns its stdout and stderr.
- chmod +x
- A macOS and Linux command that makes a file executable so it can run as a program. With a shebang line, `chmod +x kc.js` lets you run `./kc.js low`.
- Chunk
- One piece of data passing through a stream. A program handles one chunk, lets go of it and moves on.
- CLI (command-line interface)
- A program you use by typing commands in a terminal, such as `npm`, `git` or Kettle & Crane's `kc-stock`.
- CommonJS
- Node's older module system, which loads code with `require` and provides the `__dirname` and `__filename` variables. Modern code usually uses ES modules (`import`/`export`) and `import.meta.dirname` instead.
- console.table
- Prints an array of objects as a table, with one row per object and one column per property.
- crlfDelay
- A `readline` option; setting `crlfDelay: Infinity` makes a Windows line ending (`\r\n`) count as a single line break. It is a good habit to include it whenever reading lines from a stream.
- Current working directory
- The folder a program was started from, returned by `process.cwd()`. Relative paths are looked up from there, not from the script's own folder.
D
- Default export
- A module's one main export, written `export default` and imported without braces under any name you choose. `pc` is picocolors' default export.
- Dry run
- Running a command so it shows what it would do without doing it. `kc-stock reorder --dry-run` prints the orders without sending them.
E
- ECONNREFUSED
- An error code meaning nothing is listening at that address and port, so the server is down or the URL is wrong. With `fetch` it is found in `err.cause.code`.
- EEXIST / EACCES
- File error codes: `EEXIST` means the file or folder already exists, and `EACCES` means permission was denied.
- Endpoint
- One URL an API answers, together with its method, such as `GET /prices` or `POST /reorders`.
- ENOENT
- The error code for a missing file or folder ("error, no entry"). Code often catches it on purpose, for example to start with an empty inventory.
- Environment variable
- A named text value the shell gives to every program it starts, read in Node with `process.env`. Values are always strings, or `undefined` if unset.
- Error code
- A short, fixed name on an error, such as `ENOENT`, that code can check instead of reading the message. You can add your own, like `UNKNOWN_SKU`.
- ES modules (import / export)
- JavaScript's module system, which Node uses when `package.json` has `"type": "module"`. Files share code with `export` and `import`, and can use `await` at the top level.
- Event loop
- The mechanism that runs Node's waiting callbacks one at a time when the single thread is free, handling promise callbacks first.
- Event, event emitter
- An event is a named signal that something happened. An emitter, such as `StockWatcher`, calls the listeners registered with `on` or `once` whenever it uses `emit`.
- Exit code
- The number a program hands the operating system when it ends: 0 means success and anything else means failure. Setting `process.exitCode` is preferred over calling `process.exit()`, which can cut off unfinished output; a common convention is 1 for an operational error and 2 for a usage error.
F
- fetch
- The function built into Node for making HTTP requests, returning a promise of a Response. It rejects only when there is no answer, so you must check `res.ok` for 404 or 500.
- Flag (option)
- A word starting with `-` or `--` that changes what a command does, such as `--json`, `-e` or `-h`. Some are yes/no and some take a value, like `--limit 5`.
G
- glob
- A function in `node:fs/promises` that finds files whose names match a pattern, where `*` matches any run of characters. `glob("data/*.json")` finds every JSON file in `data`.
- Global
- A name usable anywhere without an import, such as `console` and `process`. `globalThis` holds all globals, and is `window` in a browser.
H
- Headers
- Extra information in an HTTP request or response as name and value pairs, such as `Content-Type: application/json` or `Authorization`.
- highWaterMark
- How much a stream reads at a time, 64 KiB for file streams, so `orders.csv` arrives in 22 chunks.
- HTTP (Hypertext Transfer Protocol)
- The protocol of the web: how a client sends requests and a server sends back responses.
I
- I/O (input/output)
- Work done by the disk or the network rather than by JavaScript, such as reading a file or calling a server.
- import.meta.dirname
- The folder of the current module (`import.meta.filename` is its full path). Building paths from it lets a script find its data files from any folder.
- instanceof
- An operator that checks whether an object was made by a given class. It lets a `catch` tell expected errors like `InventoryError` from bugs.
- InventoryError / UsageError
- Custom error classes for the Kettle & Crane stock tool, both extending `Error`. `InventoryError` adds a `code` such as `UNKNOWN_SKU`, while `UsageError` marks a mistake in how the command was typed and leads to exit code 2.
J
- JSON
- A text format for data made of objects, arrays, strings and numbers. `JSON.parse` turns JSON text into a value and `JSON.stringify` turns a value into JSON text.
L
- libuv
- The library inside Node that hands file and network jobs to the operating system so the main thread keeps running.
- localhost
- The name every computer uses for itself as a network address. The practice server runs at `localhost:3000`.
- Lockfile (package-lock.json)
- A file npm writes that records the exact version of every installed package. Commit it so everyone gets the same code.
- Log level
- How important a log message is: `debug`, `info`, `warn` or `error`. You pick a minimum level, and messages below it are skipped.
- LTS (long-term support)
- A Node release line that gets bug and security fixes for a long time. Install the version labeled LTS and upgrade before its end-of-life date.
M
- Method
- The part of an HTTP request saying what to do: `GET` reads something and `POST` creates something.
- mkdtemp / tmpdir
- `tmpdir()` from `node:os` returns the system's temporary folder, and `mkdtemp(prefix)` creates a new, uniquely named folder inside it. Tests use them so they never touch real data.
- Mock
- A fake function that stands in for a real one and records its calls. Tests use `t.mock.method` to replace `fetch` so no server is needed.
N
- nextTick / setImmediate
- Two ways to run code soon: `process.nextTick` runs right after the current code finishes, and `setImmediate` runs on the loop's next turn. Promises and `await` are almost always enough instead.
- node --run
- Runs a script from the `scripts` section of `package.json`. It starts faster than `npm run` because it doesn't load npm.
- node -e / node -p
- Flags that run JavaScript from a string on the command line: `-e` evaluates it and `-p` also prints the result.
- Node.js
- A runtime that runs JavaScript outside the browser, built from V8 plus built-in modules for files, the network and the command line.
- node:fs/promises
- The built-in module of promise-returning file functions such as `readFile`, `writeFile`, `appendFile`, `mkdir`, `readdir`, `stat`, `copyFile`, `rename` and `rm`. Unlike the `...Sync` versions, they don't block the event loop.
- node:test
- Node's built-in test runner, started with `node --test`, which finds `*.test.js` files and files in `test/`. It provides `test`, `describe`, `beforeEach` and `afterEach`.
- NODE_ENV
- An environment variable that by convention names the mode: `development`, `production` or `test`. Libraries often log less and run faster in `production`.
- node_modules
- The folder where npm puts a project's installed packages. Never edit or commit it, because npm rebuilds it.
- Non-blocking I/O
- Starting file or network work and carrying on with other code until it finishes. It's why one Node program can serve many people at once.
- npm
- The package manager that comes with Node. It downloads packages into `node_modules` and records them in `package.json` and `package-lock.json`.
- npm ci
- Installs exactly what the lockfile says, deleting `node_modules` first and never changing the lockfile. Use it on a new computer or a server.
- npm link
- Installs your package globally as a link to its folder, so the command named in the `bin` field of `package.json` works in any terminal. `npm unlink -g` removes it.
O
- Object.freeze
- Makes an object read-only so no code can change it by accident. `loadConfig` returns a frozen config.
- Operational / programmer error
- An operational error is an expected problem in normal use, like a missing file, so catch it and tell the user what to do. A programmer error is a bug, so let the program stop and fix the code.
- Optional chaining
- Writing `?.` gives `undefined` instead of throwing when the value before it is missing, such as an error with no `code`.
P
- package.json
- A project's settings file: its name, version, type, scripts, dependencies, `bin` and `engines`.
- parseArgs
- A function from `node:util` that sorts command-line words into options (`values`) and other words (`positionals`). An unknown option throws an error with an `ERR_PARSE_ARGS_` code.
- path module
- A built-in module that builds and takes apart file paths correctly on every operating system. `join` glues parts together and `resolve` gives an absolute path.
- picocolors
- A small npm package that colors terminal text, used to show low-stock items in red. Node's `styleText` does the same without a package.
- pino
- A logging library for larger apps that writes structured JSON logs, one object per line, much like a simple hand-written logger does.
- Pipe
- The `|` character in a terminal, which feeds one program's output into the next program's input, as in `cat orders.csv | node count.js`.
- pipeline
- A function from `node:stream/promises` that connects streams in order and returns a promise. It handles backpressure and closes everything if one stream fails.
- Port
- A number that tells apart programs listening on the same computer. The practice server listens on port 3000.
- Positional argument
- A command-line word that isn't an option, like `low` or a SKU. Its meaning comes from its position.
- process
- A global object describing the running program: its Node version, platform, folder, arguments (`argv`), environment and exit code. It is also an event emitter.
- promisify
- A function from `node:util` that turns an old-style callback function into one that returns a promise, such as `execFile`.
Q
- Query string
- The `?name=value&...` part at the end of a URL. `new URL()` and `searchParams.set` build it safely, encoding spaces and `&`.
R
- Readable / Writable / Transform stream
- A Readable stream is one data comes out of, a Writable one data goes into, and a Transform changes data passing through, like `createGzip()`.
- readline
- A built-in module whose `createInterface` turns a Readable stream into complete lines. The promise version has `question()` to ask the user something.
- rename (fs)
- A `node:fs/promises` function that renames or moves a file. Within one folder it happens all at once, which is what makes atomic writes work.
- REPL
- Node's interactive prompt, started by typing `node` alone. It runs each line you type and prints the result; `.exit` leaves it.
- Request / response
- What a client sends to a server (method, URL, headers, body) and what the server sends back (status code, headers, body).
- Runtime
- A program that runs code written in a language and gives it built-in objects. Node and the browser are two runtimes for JavaScript.
S
- Secret
- A value that gives access to something, like Kettle & Crane's API token. Keep it in environment variables or `.env`, never in code, Git or logs.
- Server-side (back end)
- Code that runs on a server rather than in the visitor's browser.
- setInterval / setTimeout (timers)
- `setTimeout(fn, ms)` runs `fn` once after a delay, and `setInterval(fn, ms)` runs it every `ms` milliseconds until `clearInterval` stops it. `setTimeout` from `node:timers/promises` is a promise version, used here as `sleep`.
- Shebang
- A first line, `#!/usr/bin/env node`, telling macOS and Linux to run the file with Node. Combined with `chmod +x` it lets you type `./kc.js`.
- Signal
- A message from the system to a program. Pressing Ctrl+C sends `SIGINT`, and listening for it lets your code tidy up before calling `process.exit(130)`.
- SKU (stock-keeping unit)
- The code that identifies a product in the inventory, such as `ESP-5LB` for House Espresso 5 lb.
- Spec reporter, TAP
- The spec reporter is `node --test`'s ✔/✖ format for terminals. TAP (Test Anything Protocol) is a plain format other tools can read, used when output goes to a file.
- Stack trace
- The error's name, message and `at ...` lines showing where it was thrown. Show it only at debug level, not to ordinary users.
- Status codes (200, 201, 404, 500)
- The number in a response saying how a request went: 200 OK (it worked, here's the data), 201 Created (a new thing was made), 404 Not Found (nothing at that URL) and 500 Internal Server Error (the server broke; any 5xx is the server's fault).
- stdin / stdout / stderr
- A program's three standard channels: input (what the user types or another program sends), output (the real results) and error (messages and warnings). `console.log` writes to stdout and `console.error` to stderr.
- Stream
- Data handled in chunks as it arrives instead of all at once, so memory stays small even for huge files.
- Structured logging
- Writing each log entry as data, such as one JSON object per line, so people can read it and programs can search it.
- styleText
- A function from `node:util` that wraps text in the codes a terminal uses for color. It skips the codes when output isn't a terminal.
- Subcommand
- The word after a tool's name that picks which job to do, as in `kc-stock low` or `npm install`.
T
- Test isolation
- Making every test start from a clean state, such as its own temporary folder, so tests don't affect real data or each other.
- TTY
- A terminal. `process.stdout.isTTY` is `true` when output goes to a terminal, and `process.stdin.isTTY` is `true` when a person is typing.
U
- Unhandled rejection
- A rejected promise nobody catches, or an error thrown in a callback that nothing catches (an uncaught exception). Node exits with code 1, and `process` events let you log it first.
- Usage error
- A mistake in how a command was typed, such as an unknown option or subcommand. By convention it exits with code 2 and prints the help text.
V
- V8
- Chrome's JavaScript engine, which Node uses to turn JavaScript into fast machine code.
- Version manager
- A tool such as nvm or fnm that installs several Node versions side by side and switches between them with one command.
W
- Watch mode
- Rerunning a program automatically whenever you save a file, started with `node --watch hello.js`. `node --test --watch` does this for tests.
Z
- zlib / gzip
- `node:zlib` is Node's built-in compression module. `createGzip()` is a Transform stream that compresses data, and `createGunzip()` reverses it.