Cloudflare Workers now implement three more Node.js APIs, extending the reach of npm packages that depend on them. The additions build on earlier support for AsyncLocalStorage, EventEmitter, Buffer, assert and parts of util.

  • Node.js Streams
  • Path
  • StringDecoder

All three are available in the open-source Workers runtime that powers Cloudflare Workers, both in local development and in deployed Workers. To use them, enable the nodejs_compat compatibility flag for your Worker.

Streams

The Node.js streams API predates the WHATWG ReadableStream standard. The Workers runtime now carries a full implementation derived directly from the official Node.js project implementation.

import {
  Readable,
  Transform,
} from 'node:stream';

import {
  text,
} from 'node:stream/consumers';

import {
  pipeline,
} from 'node:stream/promises';

// A Node.js-style Transform that converts data to uppercase
// and appends a newline to the end of the output.
class MyTransform extends Transform {
  constructor() {
    super({ encoding: 'utf8' });
  }
  _transform(chunk, _, cb) {
    this.push(chunk.toString().toUpperCase());
    cb();
  }
  _flush(cb) {
    this.push('\n');
    cb();
  }
}

export default {
  async fetch() {
    const chunks = [
      "hello ",
      "from ",
      "the ",
      "wonderful ",
      "world ",
      "of ",
      "node.js ",
      "streams!"
    ];

    function nextChunk(readable) {
      readable.push(chunks.shift());
      if (chunks.length === 0) readable.push(null);
      else queueMicrotask(() => nextChunk(readable));
    }

    // A Node.js-style Readable that emits chunks from the
    // array...
    const readable = new Readable({
      encoding: 'utf8',
      read() { nextChunk(readable); }
    });

    const transform = new MyTransform();
    await pipeline(readable, transform);
    return new Response(await text(transform));
  }
};

The example creates a stream.Readable and a stream.Transform. The readable emits a series of individual strings, which pass through the transform that uppercases them and appends a newline as the final chunk. Developers already using standard WHATWG streams in Workers should find the pattern familiar.

The practical effect is that modules built on Node.js streams can run unchanged. One example is split2, a utility that re-chunks a stream of data so each line becomes its own chunk. It is downloaded over 13 million times each week and has more than a thousand direct npm dependents, plus many indirect ones. Previously, using it in a Worker meant also bundling a large, complicated streams polyfill; now it works directly, with no modifications and no polyfills, cutting thousands of lines from the Worker.

import {
  PassThrough,
} from 'node:stream';

import { default as split2 } from 'split2';

const enc = new TextEncoder();

export default {
  async fetch() {
    const pt = new PassThrough();
    const readable = pt.pipe(split2());

    pt.end('hello\nfrom\nthe\nwonderful\nworld\nof\nnode.js\nstreams!');
    for await (const chunk of readable) {
      console.log(chunk);
    }

    return new Response("ok");
  }
};

Path

The Path API supplies utilities for working with file and directory paths.

import path from "node:path"
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');

// Returns: '/foo/bar/baz/asdf'

One difference from Node.js: the path.win32 variants are not implemented in Workers and will throw an exception.

StringDecoder

StringDecoder is a legacy utility that predates the WHATWG TextEncoder/TextDecoder API and serves roughly the same function. Node.js' stream implementation uses it, along with a number of popular npm modules, to decode UTF-8, UTF-16, Latin1, Base64 and Hex data.

import { StringDecoder } from 'node:string_decoder';
const decoder = new StringDecoder('utf8');

const cent = Buffer.from([0xC2, 0xA2]);
console.log(decoder.write(cent));

const euro = Buffer.from([0xE2, 0x82, 0xAC]);
console.log(decoder.write(euro)); 

In most cases a Worker should continue using the standard TextEncoder/TextDecoder APIs. StringDecoder is now available directly, however, so Workers no longer need polyfills to cover it.

Preview: the NodeJsCompatModule type

Workers can already bundle multiple assets—ESM and CommonJS modules, JSON, text and binary files. A new module type, NodeJsCompatModule, is now in preview.

The type is designed to emulate a Node.js environment as closely as possible. Inside such modules, Node.js globals including process, Buffer and even __filename are present. Crucially, it allows require() of the Node.js core API implementations without the node: specifier prefix. That broadens compatibility with npm packages that expect Node.js globals or import core APIs without the prefix.

Support has landed in the open-source workerd runtime. Deeper Wrangler integration is coming.

Compatibility and roadmap

New Node.js APIs are added monthly and appear under the nodejs_compat flag; no action is required and there is no need to change your compatibility date. Developers with an npm package or API they want supported can share it in the Cloudflare Developers Discord.