Node Fibers

5.0.3 · deprecated · verified Sun Apr 19

Fibers is a Node.js module that enables cooperative multi-tasking, often referred to as coroutines, by providing an API to jump between multiple call stacks within a single thread. It allows developers to write asynchronous code in a synchronous, blocking style, making it easier to integrate with older synchronous libraries. Originally developed in early 2011 for Node.js v0.1.x, the module's utility has largely been superseded by the standardization of native JavaScript features like Promises, async/await, and Generators. The current stable version is 5.0.3, although its compatibility is limited to Node.js v14.x and older, specifically not supporting v16.0.0 or later due to V8 engine changes. The project maintainer actively recommends avoiding its use due to its obsolescence and the inherent difficulty in maintaining compatibility with the rapidly evolving V8 engine and Node.js platform, which makes its long-term viability uncertain. It does not follow a regular release cadence, with updates primarily driven by critical compatibility fixes for older Node.js versions. A key differentiator was its ability to bring synchronous-looking code to asynchronous environments, a niche now robustly filled by modern JS concurrency primitives. Given its age and the availability of superior native alternatives, it is largely considered a legacy solution.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the basic usage of `fibers` by creating a fiber, starting its execution, yielding control back to the main thread, and then resuming the fiber multiple times.

const Fiber = require('fibers');

console.log('Main thread start');

const myFiber = Fiber(function() {
  let counter = 0;
  while (true) {
    console.log(`Fiber step ${++counter}`);
    if (counter >= 3) {
      console.log('Fiber exiting');
      break; // Exit the fiber
    }
    Fiber.yield(); // Pause fiber, return to caller
  }
});

console.log('Starting fiber...');
myFiber.run(); // Run until first yield or completion
console.log('Back in main thread after first yield');

myFiber.run(); // Resume fiber
console.log('Back in main thread after second yield');

myFiber.run(); // Resume fiber
console.log('Back in main thread after third yield');

if (!myFiber.isFinished()) {
  myFiber.run(); // In case it hasn't finished (e.g., if break condition isn't met)
}
console.log('Main thread end');

view raw JSON →