npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@mrwinston/fibers

v0.2.0

Published

Fibers for stock Node.js 24/26 on x64 Linux: node-fibers' native core (libcoro, one OS thread) with a promise-based API (Fiber.run / Fiber.await)

Readme

@mrwinston/fibers

Fibers for stock Node.js 24 and 26 on x64 Linux. Call promise-returning code from a plain synchronous function: only the calling fiber waits, while the event loop and every other fiber keep running.

import { Fiber } from "@mrwinston/fibers";
import { readFile } from "node:fs/promises";

const readText = Fiber.wrap(readFile); // looks synchronous, doesn't block the thread

function loadConfig(path) {
	// a plain function, no async/await
	return JSON.parse(readText(path, "utf8"));
}

const config = await Fiber.run(() => loadConfig("config.json"));

[!WARNING] Alpha. Read Limits before using this in production. Prefer async/await wherever you can. Use fibers only where synchronous code, such as code shared between client and server, has to call async code.

The native core is derived from node-fibers, which no longer works on current Node.js. It needs no patched Node: it runs on the official binaries.

Contents

Requirements

  • Node.js 24 or 26. Prebuilt binaries ship for both. Other versions build from source on install, and load only if their thread-local variables are known (see Upgrading Node.js).
  • x64 Linux with glibc 2.34 or later (Debian 12, Ubuntu 22.04, RHEL 9, Amazon Linux 2023, or later). Not macOS, Windows, arm64 or musl (Alpine).
  • An unstripped node executable. The addon reads the binary's symbol table. Official builds and nvm/fnm/Volta downloads have it. Some distribution packages strip it, and the addon then refuses to load with ERR_FIBER_UNSUPPORTED_NODE.
  • No CET shadow stacks. A node built with shadow stacks (SHSTK) breaks any stack switching.

Install

npm install @mrwinston/fibers
# or: pnpm add @mrwinston/fibers / yarn add @mrwinston/fibers

On Node 24 and 26 the install uses the prebuilt binary and compiles nothing. On other versions it compiles with node-gyp, which needs g++, make and python3.

Fibers only works on x64 Linux, but the package installs on every platform. This lets an app that also runs elsewhere (on a developer's Mac, for example) list it as a dependency. On any other platform the install succeeds without building anything, and the package does not work there: importing it throws ERR_FIBER_UNSUPPORTED_PLATFORM. Import it only on x64 Linux.

The package is CommonJS with an ES module entry that re-exports it, so import and require load the same copy. Only one copy may be loaded per process; a second copy throws ERR_FIBER_ALREADY_LOADED when it loads (check with npm ls @mrwinston/fibers).

Usage

Run synchronous code in a fiber

Fiber.run(fn) starts a fiber and returns a promise of fn's result. Inside the fiber, Fiber.await(promise) suspends only that fiber until the promise settles. It returns the value or throws the rejection:

const user = await Fiber.run(() => {
	const response = Fiber.await(fetch("https://example.com/user/1"));
	if (!response.ok) throw new Error(`HTTP ${response.status}`);
	return Fiber.await(response.json());
});

fn must be a plain function. If it returns a promise (an async function, for example), the promise from Fiber.run rejects with ERR_FIBER_RUN_RETURNED_PROMISE.

Wrap async APIs once, call them synchronously

Fiber.wrap(fn) turns a promise-returning function into one that suspends the calling fiber. This is the usual way to give shared synchronous code a server-side implementation:

// shared code: written synchronously, runs as-is on the client
function priceFor(Products, id) {
	const product = Products.findOne({ _id: id });
	return product.price * 1.21;
}

// server: the same interface, backed by the async MongoDB driver
const Products = {
	findOne: Fiber.wrap((query) => collection.findOne(query)),
};

app.get("/price/:id", async (req, res) => {
	res.json(await Fiber.run(() => priceFor(Products, req.params.id)));
});

A wrapped function keeps this. Called outside a fiber, or anywhere Fiber.await would throw, it throws before calling fn, so the work never starts unawaited.

Concurrency

Each fiber suspends on its own, so many requests can wait at once on one thread:

const results = await Promise.all(ids.map((id) => Fiber.run(() => priceFor(Products, id))));

A fiber can start other fibers (Fiber.run inside a fiber), and await them with Fiber.await(Fiber.run(...)).

AsyncLocalStorage, workers and custom promises

  • Each fiber has its own AsyncLocalStorage context. A fiber starts in the context of its Fiber.run caller and keeps it across awaits.
  • Works in worker threads. Each thread has its own fibers, pool, pool size and refused-await handler. A new worker starts with the pool size of the thread that created it. The stack size is one setting for the whole process.
  • Fiber.run and Fiber.await use the engine's Promise, even when the global Promise was replaced (bluebird and similar).

Modules with top-level await

When require() runs in a fiber, the module's top level may use Fiber.await. While it is suspended there, require() of that module (or of a module still requiring it) from another fiber or the root throws ERR_FIBER_REQUIRE_IN_PROGRESS, instead of returning half-initialized exports. Require shared modules before the fibers that use them start. import is not affected: it evaluates modules outside fibers.

API

All functions are static methods of Fiber. TypeScript types are included.

Fiber.run<T>(fn: () => T): Promise<T>

Runs fn in a new fiber. fn runs synchronously up to its first Fiber.await. The promise resolves with fn's return value or rejects with what it throws. Rejects with ERR_FIBER_RUN_RETURNED_PROMISE if fn returns a promise. Rejects with a RangeError with code ERR_FIBER_STACK_ALLOC if no stack can be mapped.

Fiber.await<T>(value: T | PromiseLike<T>): T

Inside a fiber: suspends the fiber until value (a promise, thenable or plain value) settles, then returns its value or throws its rejection. Outside a fiber (ERR_FIBER_AWAIT_OUTSIDE_FIBER), and in the places listed under Where Fiber.await throws, it throws without suspending.

Fiber.wrap<A, R>(fn: (...args: A) => R | PromiseLike<R>): (...args: A) => R

Returns a synchronous version of fn for use inside fibers. It is equivalent to (...args) => Fiber.await(fn(...args)), but it checks first whether it may suspend, and throws before calling fn if not.

Fiber.inFiber(): boolean

Whether the caller is running inside a fiber.

Fiber.stats(): FiberStats

Counters for the current JS thread:

| field | meaning | | --------------- | ---------------------------------------------------------------------------- | | live | fibers started and not finished | | fibersCreated | fibers created so far (finished ones are reused) | | pooled | finished fibers that kept their stack memory, ready for reuse | | released | finished fibers whose stack memory was released (beyond the pool size) | | poolSize | the current pool size (see setPoolSize) | | stackSize | the fiber stack size in bytes, the same in every thread (see setStackSize) | | switches | switches between fibers since the addon loaded |

Fiber.setStackSize(bytes: number): void

Sets the stack size of fibers created afterwards. Default and minimum: 2 MiB; maximum: 1 GiB. JS gets all but 1 MiB, which is kept for C++ frames, so by default a fiber can recurse about as deep as the main thread. A runaway recursion uses that much memory before its RangeError. Node's --stack-size does not apply to fibers. Call it before the first Fiber.run in the process; afterwards it throws ERR_FIBER_STACK_SIZE_LOCKED.

Fiber.setPoolSize(count: number): void

How many finished fibers keep their stack memory for fast reuse. Default: 120. Finished fibers beyond that release their stack's pages back to the OS. Set per JS thread; a worker starts with the value of the thread that created it.

Fiber.setRefusedAwaitHandler(handler?: (reason, refusal) => unknown): void

When Fiber.await throws instead of suspending, nobody waits for its promise. If that promise later rejects, handler(reason, refusal) receives the rejection and the error the refused await threw, for example to log both. By default (or with undefined) the rejection is ignored, so it can't crash the process as an unhandled rejection. The same goes for a promise that fn returns to Fiber.run (ERR_FIBER_RUN_RETURNED_PROMISE): nobody waits for it either, and if it rejects the handler gets that rejection, with an ERR_FIBER_RUN_RETURNED_PROMISE error as refusal. Whatever the handler throws does become an unhandled rejection. Set per JS thread.

Fiber.setRefusedAwaitHandler((reason, refusal) => {
	logger.warn({ reason, refusal }, "rejected promise of a refused Fiber.await");
});

Where Fiber.await throws

Besides outside a fiber, Fiber.await (and every Fiber.wrap'd function) throws instead of suspending in places where suspending would corrupt state shared with other fibers:

| where | code | | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- | | inside an AsyncResource scope the fiber entered itself (runInAsyncScope, bind, EventEmitterAsyncResource) | ERR_FIBER_AWAIT_IN_ASYNC_SCOPE | | inside JS run by the inspector (Session#post("Runtime.evaluate"), the DevTools console) | ERR_FIBER_AWAIT_IN_MICROTASKS_SCOPE | | inside code that vm evaluates (vm.runIn*Context, vm.Script#runIn*Context, vm.SourceTextModule#evaluate) | ERR_FIBER_AWAIT_IN_VM |

What still works with vm: awaiting before or after the vm call, and in a fiber that the vm code starts itself (Fiber.run inside the vm code), which has its own stack.

Loading the package wraps vm.Script.prototype.runInContext and .runInThisContext (every vm.runIn* goes through them) and vm.Module.prototype.evaluate (with --experimental-vm-modules). The wrappers count evaluations in progress on the current fiber, and Fiber.await compares the count with 0, at no measurable cost.

Not covered:

  • references to those methods taken before the package was loaded;
  • functions that belong to a vm context but are called outside a vm evaluation (from vm.compileFunction, or created by vm code and called later). These run as plain calls of the fiber.

Why vm is refused: a vm call is a synchronous step of its caller. With timeout or breakOnSigint, Node's watchdog terminates whatever JS runs when it fires, and a fiber suspended inside past the timeout aborted the process.

Error codes

Errors from this package carry a code and a stack trace that starts at your call of Fiber.run, Fiber.await, a Fiber.wrap'd function or Fiber.set*. The exceptions are ERR_FIBER_RUN_RETURNED_PROMISE when fn returns a promise only after it first suspended (that error shows the async callers of Fiber.run), and the load-time codes, which are thrown by the import or require of the package.

| code | thrown by | meaning | | ------------------------------------- | --------------------------------- | ---------------------------------------------------------------------------- | | ERR_FIBER_RUN_RETURNED_PROMISE | Fiber.run (rejection) | fn returned a promise; pass a synchronous function | | ERR_FIBER_AWAIT_IN_ASYNC_SCOPE | Fiber.await, wrapped functions | see Where Fiber.await throws | | ERR_FIBER_AWAIT_IN_MICROTASKS_SCOPE | Fiber.await, wrapped functions | same | | ERR_FIBER_AWAIT_IN_VM | Fiber.await, wrapped functions | same | | ERR_FIBER_REQUIRE_IN_PROGRESS | require() | another fiber is still evaluating that module (see Modules with top-level await) | | ERR_FIBER_AWAIT_OUTSIDE_FIBER | Fiber.await, wrapped functions | called outside Fiber.run | | ERR_FIBER_STACK_SIZE_LOCKED | Fiber.setStackSize | called after the first Fiber.run in the process | | ERR_FIBER_STACK_ALLOC | Fiber.run (RangeError) | no memory could be mapped for a fiber stack | | ERR_FIBER_ALREADY_LOADED | import / require | another copy of the package is already loaded in this process | | ERR_FIBER_UNSUPPORTED_PLATFORM | import / require | not x64 Linux | | ERR_FIBER_UNSUPPORTED_NODE | import / require | this node binary can't be used: stripped, unknown thread-locals, or an unexpected layout; the message says which |

Errors for invalid arguments (TypeError, RangeError) have no code.

Limits

  • A fiber always runs to completion. It can't be cancelled or restarted. A fiber that awaits a promise that never settles stays suspended until its thread ends, with its stack and everything it references; the garbage collector can't free it.
  • Memory per fiber. Each live fiber reserves 2 MiB of virtual memory and 2 memory mappings. With the default vm.max_map_count (65530), about 30,000 fibers can be suspended at once. There is no concurrency cap; beyond that, Fiber.run rejects with a RangeError.
  • Stacks keep their address. Beyond poolSize, finished fibers release their memory (RSS and commit charge go back), but their address range and mappings stay until the thread ends, so the mapping count stays at its peak. About 15 KB per peak-concurrent fiber also stays inside V8. Stacks are kept because V8 stores per-thread data, including the stack limit, for each fiber; moving a stack would require discarding that data, which breaks the CPU profiler.
  • Process exit. Suspended fibers end without running their finally blocks.
  • CPU profiles don't include samples taken while a fiber runs.
  • Wasm code memory is not reclaimed. The addon turns on --no-wasm-code-gc, because V8 aborts once fetch() (which uses wasm) runs while fibers are suspended. See FIBERS_WASM_CODE_GC below.
  • No JSPI. Loading the package removes WebAssembly.promising and WebAssembly.Suspending (JavaScript Promise Integration), so code that checks for them does what it does on an engine without JSPI. Other WebAssembly keeps working. During a garbage collection V8 scans the stacks of JSPI once for every suspended fiber, which moves the objects on them more than once and crashes the process. vm contexts lose the two functions too, before code first runs in them. Don't use references to them taken before the package was loaded.
  • C++ state across a suspending callback. When C++ calls JS that suspends (a toJSON or getter that awaits, for example), other fibers run while that C++ frame waits. Suspending inside JSON.stringify, JSON.parse revivers, v8.serialize, structuredClone, proxy traps and require(esm) is tested with many fibers at once. While one fiber is suspended inside Error.prepareStackTrace, other fibers get the default stack format.

Upgrading Node.js

The addon swaps V8's internal thread-local variables per fiber, and checks at load time that it knows every thread-local of the running node binary. A new Node.js version can add some. The addon then refuses to load, on purpose, with ERR_FIBER_UNSUPPORTED_NODE and a message such as:

refusing to load: this node binary has thread-local variables that fibers does not know: ...

It needs a new release of this package that classifies them; test a Node.js upgrade before deploying it. node -e "import('@mrwinston/fibers').then(m => console.log(m.Fiber._tlsLayout()))" prints how the running binary's thread-locals are handled.

Environment variables

| variable | effect | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | FIBERS_WASM_CODE_GC=1 | Keeps V8's wasm code GC on. Reclaims wasm code memory, but fetch() while fibers are suspended then aborts the process. | | FIBERS_ALLOW_UNKNOWN_TLS=1 | Loads despite unknown thread-locals. For diagnosis only; never in production. | | FIBERS_NO_CHECKS=1 | Skips the safety checks done at every switch. |

How it works

Every fiber runs on the JS thread's own OS thread, on its own stack (from libcoro, as in node-fibers). Switching fibers releases V8 with v8::Unlocker and re-acquires it with v8::Locker, so V8 treats each fiber as a separate thread.

V8 keeps the identity of the current thread (its thread id, stack start and a few scope variables) in C++ thread_local variables, which no API reaches. The addon finds every thread-local of the node executable through its ELF symbol table, classifies each one by name, and saves and restores the per-fiber ones at every switch:

| class | variables | at a switch | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | | swap | V8 thread_id, thread_stack_start, assert-scope bits, wasm code-ref scope, Node's is_in_uncaught_exception / is_retrieving_js_stacktrace | saved and restored per fiber | | set by Isolate::Enter | g_current_isolate_, per-isolate thread data, marking barrier, local heap | must be empty after a full exit | | must be zero | compiler, wasm trap handler, layout-change and dlopen scopes | checked | | leave | OS-thread caches, certificate store, library state | untouched (same OS thread) |

Other details:

  • Finished fibers are reused, never deleted. Each keeps the V8 thread id it got first, because V8 hands ids out from a process-wide counter and aborts after 2^31.
  • Each fiber's JS stack limit comes from its own stack, not from --stack-size.
  • AsyncLocalStorage's context is saved per fiber, and TerminateExecution inside a fiber is passed on to its caller. Suspended fibers are ended when the environment shuts down.

| file | contents | | ------------------------- | -------------------------------------------------------------------------------- | | native/libcoro/ | libcoro, as vendored by node-fibers: stack allocation and the x86-64 switch | | native/coroutine.{h,cc} | coroutines on libcoro stacks: pool, transfer, finish | | native/fibers.cc | the native core: start, suspend, resume, Node/V8 integration | | native/tls.{h,cc} | finds, checks and swaps V8's thread-locals; cites the V8 source behind each rule | | src/ | the Fiber API on top of the native core, and the vm/JSPI/require guards |

Performance

Node 26.13.1, 16 CPUs (bench/bench.mjs; results vary ±20% between runs):

| | fibers | async/await | | --------------------------------------------------------- | ----------------- | ------------- | | Fiber.await of a resolved value | 1.05–1.14 µs | 0.04 µs | | Fiber.run(() => 1) | 1.5 µs | 0.1–0.2 µs | | 1024 fibers awaiting setImmediate, per await | 2.7–2.9 µs | 0.3–0.5 µs | | 500 workers (CPU + 1 ms timer + setImmediate), 2 s | 76–87k ops/s | 95–120k ops/s | | same: event-loop lag p99 / 5 ms ping delay p95 | 8–10 / 6.6–7.8 ms | 5–8 / 3–7 ms |

The cost of a switch does not grow with the number of suspended fibers.

Development

Needs g++, make, python3 and pnpm.

pnpm install
pnpm run build                    # typecheck, dist/ (tsdown), build/Release/fibers.node
pnpm run prebuilds                # prebuilds/linux-x64/node-{137,147}/ for Node 24 and 26 (via fnm)
pnpm test                         # the test suite (needs pnpm run build first)
pnpm run test:stress              # the suite under 3 GC/JIT stress settings, as on release tags
node bench/bench.mjs              # benchmark

The tests are in test/. Each <subject>.test.mjs runs with node --test and imports helpers.mjs, which fails the file if the build is older than its sources and checks after every test that no fiber is left live and nothing the test registered with track() leaked. Plain node:assert assertions check what this README promises; observed.* assertions check details it doesn't (message text, exact counters), and say so when they fail. Anything that needs its own Node flags, stack size, resource limit or environment variable, or that may crash or exit, runs in a child process: runChild("fixture-<subject>.mjs", { caseName, flags, env }) starts test/fixture-<subject>.mjs, which sends its results back with report(). readme.test.mjs checks that every error code in the source is in this README and tested, and that every API heading has a test.

CI (Bitbucket Pipelines) runs the suite on Node 24 and 26 for every push, and the stress pass on v* tags. It builds the prebuilt binaries on Debian 12, and scripts/check-prebuilds.mjs fails the pipeline if they need a newer glibc or libstdc++ than Requirements names. Pushing a v* tag that matches package.json's version publishes to npm.

prototypes/ holds earlier approaches (a V8 patch, an addon with an OS thread per fiber, and a first version of this design). They are kept for reference and are not part of the package.

License

MIT; see LICENSE. The native code is derived from node-fibers (MIT, Copyright 2011 Marcel Laverdet). native/libcoro/ is libcoro by Marc Alexander Lehmann, under the BSD 2-clause license or GPL 2+ (see native/libcoro/LICENSE).