skip to content

Bundled Tooling

What ships inside the node binary beyond the runtime: a test runner, .env loading, argument parsing and a permission model. Interviewers ask what still needs a third-party package in a new project.

on this pageshow

explore

questions

12

In Node.js, what type does every value in process.env have, and why does a check like if (process.env.CACHE_ENABLED) misfire?

level: juniorimportance: must knowfreq 55%

answer

  1. the environment the process started with
  2. one primitive type for every value
  3. a non-empty text is truthy
  4. writes are converted, too

basics

~10 s

Every process.env value is a string, or undefined when the variable is unset. CACHE_ENABLED=false yields the non-empty string 'false', which is truthy, so the branch runs; parse and compare values explicitly.

solid answer

~40 s

`process.env` is an object holding the environment the Node process was started with, and every value in it is a string; a variable that is not set reads as `undefined`. So `CACHE_ENABLED=false` gives `'false'`, `PORT=8080` gives `'8080'`, and `if (process.env.CACHE_ENABLED)` is true for any non-empty value, `'false'` and `'0'` included. The fix is to parse once at startup: compare booleans against an explicit set of strings, turn numbers into numbers with `Number.parseInt` and a `NaN` check, and fail at boot when a required variable is missing. Writing to `process.env` converts the value to a string too (`env.RETRIES = 3` stores `'3'`), and the change never reaches the shell that launched Node, although child processes spawned afterwards with the default `env` do inherit it.

code

javascript · 13 lines
javascript
// Run with: CACHE_ENABLED=false PORT=8080 node config.cjs
const { env } = require('node:process');

console.log(typeof env.PORT);            // 'string'
console.log(Boolean(env.CACHE_ENABLED)); // true: 'false' is a non-empty string

const cacheEnabled = ['1', 'true', 'yes'].includes((env.CACHE_ENABLED ?? '').toLowerCase());
const port = Number.parseInt(env.PORT ?? '3000', 10);
if (Number.isNaN(port)) throw new Error(`PORT must be an integer, got ${env.PORT}`);

env.RETRIES = 3;
console.log(typeof env.RETRIES, env.RETRIES); // string 3
console.log({ cacheEnabled, port });          // { cacheEnabled: false, port: 8080 }

go deeper

for a junior

Recall that every process.env value is a string or undefined, so 'false' and '0' are truthy, and that assignments are converted to strings.

for a middle

Explain where the values come from, which conversions assignment performs and which of them are deprecated, and how one startup parse turns text into typed, validated settings.

for a senior

Show the production angle: fail at boot on a missing or malformed variable, and know which child processes and worker threads see changes made to process.env at runtime.

for a principal

Weigh a team rule that only one module may read process.env: a single typed, audited boundary against the convenience of reading variables wherever code needs them.

## What process.env is `process.env` is a property of Node's global `process` object. It holds the **user environment** of the process: the key-value pairs the operating system handed to Node when it started (the shell, a supervisor or the platform that launched it decides what those are). Node's own documentation describes it as an object containing the user environment, see environ(7), and the Node.js learn guide describes it as the variables that were set at the moment the process was started. You do not need to import anything to read it, though `import { env } from 'node:process'` or `require('node:process').env` work as well. ## Every value is a string The operating system stores environment variables as text, and Node does not guess types for you. Whatever the variable holds arrives as a JavaScript **string**, and a variable that is absent reads as `undefined`. Values loaded from a `.env` file with `--env-file` follow the same rule: Node's dotenv documentation states that `0`, `true` and a JSON object all become literal strings. | Set in the environment | `process.env.FLAG` | Truthy in an `if`? | |---|---|---| | `FLAG=true` | `'true'` | yes | | `FLAG=false` | `'false'` | **yes** | | `FLAG=0` | `'0'` | **yes** | | `FLAG=` (empty) | `''` | no | | not set | `undefined` | no | That table is the whole bug: a **truthiness check** only distinguishes "missing or empty" from "anything else". Operators who write `CACHE_ENABLED=false` expect the cache to switch off, and the code switches it on. Numbers fail the same way, more quietly. `process.env.PORT + 1` with `PORT=8080` is `'80801'`, string concatenation rather than arithmetic, and `process.env.TIMEOUT_MS > 500` compares a string with a number through implicit conversion, which works until someone writes `500ms`. ## Writing to process.env The object is writable, and assignment has rules of its own: - **Assignment converts the value to a string.** `env.RETRIES = 3` stores `'3'`; `env.X = null` stores `'null'` and `env.X = undefined` stores `'undefined'`. Node's deprecation list (DEP0104, documentation-only) marks the implicit conversion as deprecated when the value is not a string, number or boolean, and says such assignments might throw in the future. - **Use `delete` to remove a variable.** Assigning `undefined` does not remove it; it stores the text `'undefined'`. - **Changes stay inside this process tree.** They are never reflected in the shell that launched Node. Child processes started later through `node:child_process` see them, because the `env` option of `spawn`, `exec` and `execFile` defaults to `process.env`. - **Each `worker_threads.Worker` gets its own copy** of the parent's `process.env` by default (since v11.14.0), so later changes on either side are not shared unless the worker was created to share the environment. - **On Windows, names are case-insensitive** on the main thread, so `env.TEST` and `env.test` are the same entry there. ## Parsing once at startup The robust pattern is a single configuration module that reads every variable once, when the process boots: 1. Read each variable by name in one place, so a typo shows up in one file instead of silently returning `undefined` somewhere deep in a request path. 2. Turn booleans into booleans by comparing against an explicit list such as `'1'`, `'true'` and `'yes'`, never by truthiness. 3. Turn numbers into numbers with `Number.parseInt(value, 10)` or `Number(value)` and reject `NaN`. 4. Throw at startup when a required variable is missing or malformed, so the process fails its health check before it takes traffic rather than failing on the first request that needs the value. ## Defaults: `||` versus `??` Supplying a fallback is where the string rule meets the language. `process.env.PORT || '3000'` replaces both an unset variable and an empty one, while `process.env.PORT ?? '3000'` replaces only an unset one and keeps `''`. Neither converts the type, so the result is still a string to parse. Decide deliberately whether an operator who writes `PORT=` meant "use the default" or made a mistake, and make the startup check say so. ## Seeing what the process actually reads When it is unclear which variables a service or a dependency touches, start Node with `--trace-env` (added in v23.4.0 and v22.13.0). It prints to stderr the **names** of every environment variable read, written, deleted or enumerated, including the reads Node performs internally, but never their values. `--trace-env-js-stack` adds the JavaScript stack of each access, which points at the exact module that reads a misbehaving variable. ## Common mistakes to avoid - Treating `process.env.FLAG` as a boolean because the shell value looked like one. - Doing arithmetic on `process.env.PORT` without converting it first. - Expecting `process.env.X = undefined` to unset a variable. - Expecting a variable set inside Node to be visible to the shell after the process exits. The underlying fact is small, and it is a Node fact rather than a language one: the runtime exposes the environment exactly as the operating system stores it, as text, and leaves typing and validation to your code.

  • If code sets process.env.API_URL while a Node service runs, which other processes and threads see the new value?
    The shell or supervisor that launched Node never sees it. A child process spawned afterwards through `node:child_process` does, because the `env` option defaults to `process.env`. A `worker_threads.Worker` created afterwards starts with a copy of the parent's `process.env`, but later changes on either side are not shared unless the worker was set up to share the environment.
  • Why parse environment variables into a typed object at startup instead of reading process.env wherever a value is needed?
    Because a misspelled or missing variable reads as `undefined` without any error, and a malformed one stays a string until something uses it. Parsing at boot turns both into an immediate, explicit failure before the process takes traffic, gives every value its real type once, and leaves one module to audit when someone asks what the service reads.

  • process.env.PORT is a number when the variable holds only digits.
  • Setting FLAG=false makes process.env.FLAG the boolean false.
  • Assigning process.env.X = undefined removes the variable.
  • Changing process.env inside Node updates the shell that started it.
  • Only variables listed in a .env file appear in process.env.
open as a page

In Node.js 24, which files does `node --test` run when given no file arguments, and how does it decide that each file passed?

level: juniorimportance: should knowfreq 30%

basics

~20 s

With no arguments, node --test runs every file outside node_modules named like *.test.js, _test.js or test-.js, or sitting in a test/ folder (plus .ts forms in Node 24), each in its own child process; a file passes when that process exits 0.

open as a page

In Node.js 24, what does node --env-file=.env do, and which value wins when the shell environment and several env files set the same variable?

level: middleimportance: should knowfreq 35%

basics

~20 s

node --env-file=.env reads the file before your code runs and adds its variables to process.env. A variable already set in the real environment wins over the file, and a later --env-file wins over an earlier one.

open as a page

What does setting NODE_ENV=production change in the Node.js runtime itself, and why do Node services still set it?

level: middleimportance: should knowfreq 50%

basics

~20 s

Nothing in Node itself: the runtime does not read NODE_ENV. It is a convention that libraries and frameworks read, for example to enable a template cache, so services set it for their dependencies rather than for Node.

open as a page

In Node.js `node:test`, how do `mock.fn()` and `mock.method()` record calls, and when does the original behaviour come back?

level: middleimportance: should knowfreq 28%

basics

~20 s

Both return a Proxy whose .mock property records every call's arguments, result, error and this; mocks made through the test context's t.mock are restored when the test ends, while the top-level mock keeps its mocks until mock.reset() or mock.restoreAll().

open as a page

In Node.js `node:test`, how does `mock.timers` let a test of retry or timeout logic run without waiting, and what does it not intercept?

level: middleimportance: should knowfreq 25%

basics

~20 s

mock.timers.enable() replaces setTimeout, setInterval, setImmediate, Date and a few related APIs with fakes on one virtual clock, and tick(ms) or runAll() fires due callbacks synchronously; timers destructured from node:timers and other time sources escape it.

open as a page

A platform sets NODE_OPTIONS for a Node.js 24 service whose start command also passes flags; how does Node combine them, and what surprises follow?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Node reads NODE_OPTIONS before the command line: a single-value flag on the command line overrides it, repeatable flags from NODE_OPTIONS come first, and a flag not allowed there, such as --env-file, stops Node at startup.

open as a page

In Node 24's built-in test runner, a suite passes with plain `node --test` but fails under `--test-isolation=none`. What explains it, and how do you find the culprit?

level: seniorimportance: should knowfreq 20%

basics

~20 s

By default each test file runs in its own child process, so module singletons, globals, process.env edits and top-level mocks die with the file; --test-isolation=none imports every file into one process, exposing tests that depend on shared state or order.

open as a page

Would you replace a Node 24 service's third-party test framework with the built-in `node:test` runner, and how would you decide and stage the switch?

level: principalimportance: should knowfreq 15%

basics

~20 s

Switch when the suite mostly needs what node:test ships stably, such as suites, hooks, node:assert, function and timer mocks, snapshots and reporters; keep the framework while the suite leans on module mocking or plugins, and migrate file by file.

open as a page

In Node.js, what does util.parseArgs return for a script's command-line arguments, and how does it treat an option it was not told about?

level: middleimportance: nice to knowfreq 15%

basics

~10 s

util.parseArgs turns the script's arguments into values and positionals according to an options spec whose types are only string or boolean. Its default strict mode throws ERR_PARSE_ARGS_UNKNOWN_OPTION for an option missing from that spec.

open as a page

In Node.js 24, what does running a service with --permission restrict, how do the --allow-* flags grant access back, and what does it not protect against?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

--permission makes Node deny file access, child processes, worker threads, addons, WASI and the inspector unless an --allow-* flag grants them. In Node 24 the network stays open, and the model guards trusted code, not malicious code.

open as a page

How do you make Node 24's built-in test runner fail a CI build when line coverage drops, and what can its coverage report miss?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Run node --test with --experimental-test-coverage and a threshold such as --test-coverage-lines=80, which exits with code 1 below the bar; the V8-based report omits files no test loads and, by default, test files, node_modules and core modules.

open as a page