DEV Community

Cover image for The runtime you already have: test runner, permissions, threads and TypeScript
Javi Palacios
Javi Palacios

Posted on Originally published at fjp.es

The runtime you already have: test runner, permissions, threads and TypeScript

Open almost any project's package.json and count: nodemon, dotenv, jest or vitest, ts-node, commander, chokidar. Each one solved a real problem five years ago. Today Node has an answer for nearly all of them, and the difference between knowing it and not is a node_modules heavier than the app or three scripts.

This is the second-to-last lesson and it's about exactly that: looking at what's already in the box before installing. And about deciding with judgement, because not everything the runtime ships is better than what's outside.

A test runner, with nothing installed

node:test ships with the runtime, and node --test finds your *.test.js files on its own.

// src/sum.test.js
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { add, divide } from "./sum.js";

describe("add", () => {
  test("adds two positives", () => {
    assert.equal(add(2, 3), 5);
  });
  test("fails on purpose", () => {
    assert.equal(add(2, 2), 5);
  });
});

test("divide by zero throws", () => {
  assert.throws(() => divide(1, 0), /divide by zero/);
});
Enter fullscreen mode Exit fullscreen mode
node --test
Enter fullscreen mode Exit fullscreen mode
ℹ tests 3
ℹ suites 1
ℹ pass 2
ℹ fail 1
Enter fullscreen mode Exit fullscreen mode

describe and test group, assert checks, and the summary is readable without configuring anything. And with coverage:

node --test --experimental-test-coverage
Enter fullscreen mode Exit fullscreen mode
ℹ file      | line % | branch % | funcs % | uncovered lines
ℹ  sum.js   |  80.00 |    75.00 |  100.00 | 4
ℹ all files |  80.00 |    75.00 |  100.00 |
Enter fullscreen mode Exit fullscreen mode

Four columns: lines, branches, functions and which lines are uncovered. What you need to know whether your tests test anything, without installing a reporter. And there are flags to tune it: --test-coverage-include, --test-coverage-exclude, --test-coverage-lines, --test-coverage-branches, --test-coverage-functions and --test-coverage-include-all, the last one to count files no test ever touches.

It has subtests, mock for doubles and a watch mode. What it doesn't have is Jest's or Vitest's plugin ecosystem; if your suite needs complex snapshots or UI framework integration, there are still reasons to install. For backend tests, most of the time, there aren't.

Two flags that each save a package

The plan groups them, and rightly so: same idea applied twice.

--watch replaces nodemon. It starts the process, restarts it when a file changes and tells you:

node --watch app.js
Enter fullscreen mode Exit fullscreen mode
started 1794705607053
Completed running 'app.js'. Waiting for file changes before restarting...
Change detected in '/tmp/w13en/app.js'
Restarting 'app.js'
version 2 1794705608435
Enter fullscreen mode Exit fullscreen mode

The English messages are Node's; started and version 2 are the script's. No configuration, no nodemon.json, no file-pattern list to debug: it watches what your process imports.

--env-file replaces dotenv, and you saw it in the files lesson. Here the contrast is all that's left:

node app.js
node --env-file=.env app.js
Enter fullscreen mode Exit fullscreen mode
PORT: undefined · APP_NAME: undefined
PORT: 3001 · APP_NAME: course
Enter fullscreen mode Exit fullscreen mode

Without the flag, the variables don't exist. With it, they're in process.env before your code runs, so there's no dotenv.config() and no import order to worry about.

Arguments without a library

util.parseArgs turns the command line into an object, with types and defaults.

// cli.js
import { parseArgs } from "node:util";

const { values, positionals } = parseArgs({
  allowPositionals: true,
  options: {
    name: { type: "string", short: "n" },
    verbose: { type: "boolean", short: "v", default: false },
    port: { type: "string", default: "3000" },
  },
});

if (values.verbose) console.log("verbose mode on");
console.log("name:", values.name, "· port:", values.port, "· rest:", positionals);
Enter fullscreen mode Exit fullscreen mode
node cli.js --name Ada -v extra
Enter fullscreen mode Exit fullscreen mode
verbose mode on
name: Ada · port: 3000 · rest: [ 'extra' ]
Enter fullscreen mode Exit fullscreen mode

And its best trait is that it's strict:

node cli.js --invented
Enter fullscreen mode Exit fullscreen mode
TypeError [ERR_PARSE_ARGS_UNKNOWN_OPTION]: Unknown option '--invented'. To specify a positional argument starting with a '-', place it at the end of the command after '--'
Enter fullscreen mode Exit fullscreen mode

A CLI that accepts any flag without complaining is a CLI where a typo becomes a silent default. Here the typo is an error naming exactly what doesn't belong.

TypeScript without compiling

Node can run a .ts file directly, without ts-node, tsc or a dist/ folder:

// types.ts
type Book = { title: string; pages: number };

const book: Book = { title: "Emma", pages: 474 };
console.log("book:", book.title, book.pages);
Enter fullscreen mode Exit fullscreen mode
node types.ts
Enter fullscreen mode Exit fullscreen mode
book: Emma 474
Enter fullscreen mode Exit fullscreen mode

What it does isn't compiling: it erases the types. It strips the annotations and runs the rest, and that imposes a condition worth understanding before celebrating: only syntax whose information is unnecessary at runtime qualifies. An enum doesn't qualify, because it generates code:

enum Color {
  Red,
  Green,
}
console.log(Color.Red);
Enter fullscreen mode Exit fullscreen mode
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode
Enter fullscreen mode Exit fullscreen mode

That's why TypeScript has erasableSyntaxOnly: it warns you in the editor about what the runtime will reject. With that option on, there are no surprises at deploy time.

And the limit, which matters: this is a runtime feature, not a language one. There's no type checking, no honoured tsconfig, no decorator transformation. That's what the TypeScript course is for. Here it only explains why your node index.ts works with nothing installed.

The permission model

A Node process can, by default, read any file, write anywhere and spawn child processes. --permission restricts it.

// read.js
import { readFile } from "node:fs/promises";
console.log((await readFile("./src/sum.js", "utf8")).length);
Enter fullscreen mode Exit fullscreen mode
node --permission read.js
Enter fullscreen mode Exit fullscreen mode
Error: Access to this API has been restricted. Use --allow-fs-read to manage permissions.
  code: 'ERR_ACCESS_DENIED',
Enter fullscreen mode Exit fullscreen mode

And with explicit permission, it works:

node --permission --allow-fs-read=. read.js
Enter fullscreen mode Exit fullscreen mode
146
Enter fullscreen mode Exit fullscreen mode

It's the same principle as a container or a chroot, applied to the process: everything closed, and you open what's needed. And the detail that makes it interesting: the permission model covers child processes and workers too. If your process can't spawn them, it can't escape its restrictions by creating another. That's what turns the permission into a boundary instead of a suggestion.

Work that leaves the thread

The event loop lesson ended with one sentence: CPU work gets moved off the thread. Here's how, and how much.

// workers.mjs
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";

const work = () => {
  let total = 0;
  for (let i = 0; i < 2e8; i++) total += i;
  return total;
};

if (isMainThread) {
  const empty = new Worker(new URL(import.meta.url), { workerData: "empty" });
  const t0 = performance.now();
  empty.once("message", () => {
    console.log("starting a worker costs", (performance.now() - t0).toFixed(1), "ms");
    empty.terminate();

    const t1 = Date.now();
    setTimeout(() => {}, 0);
    work();
    console.log("on the main thread: the timer waited", Date.now() - t1, "ms");

    const busy = new Worker(new URL(import.meta.url), { workerData: "cpu" });
    const t2 = Date.now();
    setTimeout(() => console.log("with a worker: the timer waited", Date.now() - t2, "ms"), 10);
    busy.once("message", (total) => {
      console.log("the worker finished at", Date.now() - t2, "ms ·", total > 0);
      busy.terminate();
    });
  });
} else if (workerData === "empty") {
  parentPort.postMessage("ready");
} else {
  parentPort.postMessage(work());
}
Enter fullscreen mode Exit fullscreen mode
starting a worker costs 18.8 ms
on the main thread: the timer waited 846 ms
with a worker: the timer waited 11 ms
the worker finished at 801 ms · true
Enter fullscreen mode Exit fullscreen mode

The same calculation, two places, a 10 ms timer watching. On the main thread, the timer that asked for a turn at 10 ms came out at 846: the service was mute for most of a second. With a worker, it came out at 11 and the calculation finished at 801. The work costs the same; what changes is who waits.

Two costs that don't show in the table: starting a worker costs about 20 ms, so one per request is worse than having none; and data crosses by structured clone, meaning it's copied. Sharing memory for real needs SharedArrayBuffer and Atomics, and that's another level.

For everything else there's child_process: real processes, with their own isolation.

// children.mjs
import { execFile, spawn, fork } from "node:child_process";
import { promisify } from "node:util";

const execFileAsync = promisify(execFile);
const { stdout } = await execFileAsync("node", ["-p", "process.version"]);
console.log("execFile returns:", stdout.trim());

const child = spawn("node", ["-e", "console.log('from the child'); process.exit(3)"]);
child.stdout.on("data", (d) => console.log("spawn stdout:", d.toString().trim()));
child.on("exit", (code) => console.log("spawn exit code:", code));
Enter fullscreen mode Exit fullscreen mode
execFile returns: v26.12.1
spawn stdout: from the child
spawn exit code: 3
Enter fullscreen mode Exit fullscreen mode

execFile accumulates the output and hands it back; spawn gives you streams and the exit code; fork starts another Node process with a message channel, and you talk to it with send and on("message").

The rule for choosing: threads for computation inside your process, processes when you want real isolation — a crash, a native dependency, another Node version. Neither is free.

Watching files, carefully

fs.watch exists and works, with more caveats than the blog posts advertise. Measured on Linux with Node 26: recursive: true does work (the macOS-and-Windows-only limitation is out of date) and a single writeFile fires two events:

event: rename · sub/new.txt
event: change · sub/new.txt
Enter fullscreen mode Exit fullscreen mode

Two events for one write, with names that don't describe what you did. That inconsistency is exactly why chokidar still makes sense: it isn't a wrapper for show, it's a buffer for platform differences.

And for the everyday case — restarting the server when a file changes — none of this is needed: node --watch ships with the runtime and replaces nodemon.

require(esm), and the mess is still there

Node lets you load an ES module from CommonJS:

// esm-module.mjs
export const version = "1.0.0";
export default function greet() {
  return "hello";
}
Enter fullscreen mode Exit fullscreen mode
// load.cjs
const mod = require("./esm-module.mjs");
console.log("keys:", Object.keys(mod));
console.log("version:", mod.version);
console.log("default:", typeof mod.default, "→", mod.default());
Enter fullscreen mode Exit fullscreen mode
keys: [ '__esModule', 'default', 'version' ]
version: 1.0.0
default: function → hello
Enter fullscreen mode Exit fullscreen mode

It works, and notice __esModule and default: the module arrives wrapped in a namespace. If the package has a default export, it's in .default, not at the root. That difference is what breaks code when a package changes format, and the reason the "dual package hazard" still has a name: a package published in both formats can end up loaded twice, with two copies of its state.

Now with your project

Everything above is demonstrated with minimal scripts. Apply it to the previous lesson's API and the order of things changes: permissions aren't opened at once, they're opened door by door, and every door tells you which flag is missing.

node --permission src/server.js
Enter fullscreen mode Exit fullscreen mode
Error [ERR_ACCESS_DENIED]: Access to this API has been restricted. Use --allow-fs-read to manage permissions.
  code: 'ERR_ACCESS_DENIED',
Enter fullscreen mode Exit fullscreen mode

It doesn't even start: it can't read its own module graph. Open the first door:

node --permission --allow-fs-read=. src/server.js
Enter fullscreen mode Exit fullscreen mode
Error: Access to this API has been restricted. Use --allow-net to manage permissions.
Enter fullscreen mode Exit fullscreen mode

Files are readable now; the port fails next, because the permission model closes the network too. And the third:

node --permission --allow-fs-read=. --allow-net src/server.js
Enter fullscreen mode Exit fullscreen mode
listening on 3000
Enter fullscreen mode Exit fullscreen mode

And it answers: curl -s http://localhost:3000/health returns {"ok":true}. Three flags and a server locked in its box.

One detail ties back to the threads section: a worker inside a process with permissions doesn't start either.

node --permission --allow-fs-read=. worker.mjs
Enter fullscreen mode Exit fullscreen mode
Error: Access to this API has been restricted. Use --allow-worker to manage permissions.
Enter fullscreen mode Exit fullscreen mode

It's the same boundary we talked about: if the process can't create workers or child processes, it can't escape its restrictions by creating another.

And the tests, on the real project. The file lives next to the service, no Express in between:

node --test
Enter fullscreen mode Exit fullscreen mode
  ✔ creates and returns a book (1.104499ms)
  ✔ a missing id throws 404 (0.566547ms)
✔ book service (3.259212ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0
Enter fullscreen mode Exit fullscreen mode

That's what splitting layers bought in the previous lesson: the service is tested without starting a server, without a database and without opening a port. The only thing you need is the runtime.

The decision: what earns a package

With all of the above, the decision table looks like this:

You used to install It ships with Node now When the package still earns it
nodemon node --watch Never, for development
dotenv --env-file If you need interpolation or schema validation
jest / mocha node --test UI, complex snapshots, plugin ecosystem
ts-node Type stripping If you need transformation (decorators, enum)
commander util.parseArgs CLIs with subcommands and generated help
chokidar fs.watch Almost always, because of cross-platform inconsistency

The useful question isn't "is this fashionable?" but "what does this dependency cost me to maintain?". A library that solves a problem the runtime already solves is debt: upgrades, security advisories, a package.json that grows and nobody prunes.

And the other side: a dependency that saves you two weeks of work is doing its job. The criterion isn't "fewer is better", it's knowing what you're paying for.

What you take from this lesson

  • node --test is a complete test runner, with summary, coverage and subtests.
  • --watch and --env-file replace nodemon and dotenv with no configuration.
  • util.parseArgs gives typed arguments and, more importantly, fails on what it doesn't know.
  • Type stripping runs .ts by erasing types; enum and friends aren't erasable, and erasableSyntaxOnly warns you first.
  • --permission closes the process by default and opens it with --allow-*; it covers files, children and workers.
  • A worker costs about 20 ms to start and avoids half-second stalls on the main thread.
  • execFile, spawn and fork: processes for isolation, threads for computation.
  • fs.watch works, fires duplicate events, and that's why chokidar is still alive.
  • require(esm) loads ES modules, but the default export arrives in .default.
  • Permissions open door by door: files, network, workers and child processes, each with its own flag.
  • The previous lesson's service is tested with node --test, no server, no database, no port.
  • The question isn't how many dependencies you have, but which ones you're paying for without needing them.

Your API now validates, logs, shuts down without dropping requests, and knows which parts of the runtime it doesn't need to install. One thing is missing, and it isn't about the runtime: a backend that only talks to its own database isn't a backend. The last lesson is about calling other services — with a timeout, with retries that don't charge a customer twice, and with tests that need no internet — and then the course really does close.

Never stop coding!

Top comments (0)