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

worker-fs-mount

v0.1.2

Published

Mount WorkerEntrypoints as virtual filesystems in Cloudflare Workers

Downloads

146

Readme

worker-fs-mount

Mount WorkerEntrypoints as virtual filesystems in Cloudflare Workers. This package provides a drop-in replacement for node:fs/promises that intercepts filesystem calls and redirects them to your WorkerEntrypoint implementations via jsrpc.

Features

  • Simple setup - Just add an alias to wrangler.toml and your existing node:fs/promises code works
  • Multiple mount sources - Works with ctx.exports, service bindings, and Durable Objects
  • Full fs coverage - Supports 20+ filesystem operations (read, write, stat, readdir, mkdir, rm, rename, etc.)
  • TypeScript-first - Full type definitions with strict types
  • Cross-mount safety - Properly handles operations across mount boundaries

Installation

npm install worker-fs-mount

Setup

Add the following alias to your wrangler.toml:

[alias]
"node:fs/promises" = "worker-fs-mount/fs"
"node:fs" = "worker-fs-mount/fs-sync"

This replaces node:fs/promises and node:fs imports with our mount-aware implementations at build time. The node:fs alias is optional - only needed if you use synchronous fs methods.

Quick Start

import { env } from 'cloudflare:workers';
import { mount } from 'worker-fs-mount';
import fs from 'node:fs/promises';

// Mount at module level using importable env
mount('/mnt/storage', env.STORAGE_SERVICE);

export default {
  async fetch(request) {
    // Standard fs operations are automatically intercepted
    await fs.writeFile('/mnt/storage/data.json', JSON.stringify({ hello: 'world' }));
    const content = await fs.readFile('/mnt/storage/data.json', 'utf8');

    // Non-mounted paths work normally
    await fs.readFile('/tmp/local.txt');

    return new Response(content);
  }
};

How It Works

With the wrangler alias configured, every node:fs/promises import is replaced with our implementation. Each filesystem call checks if the path falls under a mounted location:

fs.readFile('/mnt/storage/file.txt')
       ↓
Is '/mnt/storage' mounted? → YES → Call stub.readFile('/file.txt') via jsrpc
       ↓
Is '/tmp/file.txt' mounted? → NO → Use native node:fs/promises

Both import styles work:

import fs from 'node:fs/promises';
import { readFile, writeFile } from 'node:fs/promises';

// Both are intercepted for mounted paths
await fs.readFile('/mnt/storage/file.txt');
await readFile('/mnt/storage/file.txt');

Mount Sources

Service Bindings

// wrangler.toml
// [[services]]
// binding = "STORAGE"
// service = "storage-worker"

mount('/mnt/storage', env.STORAGE);

Same-Worker Entrypoints

export class MyFilesystem extends WorkerEntrypoint {
  async readFile(path) { /* ... */ }
  // ...
}

export default class extends WorkerEntrypoint {
  async fetch() {
    mount('/mnt/local', this.ctx.exports.MyFilesystem);
  }
}

Durable Objects

Access via ctx.exports (recommended) - run wrangler types to generate types:

export class StorageDO extends DurableObject implements WorkerFilesystem {
  // ... implement filesystem methods
}

export default class extends WorkerEntrypoint<Env> {
  async fetch() {
    // ctx.exports provides typed access to your exported Durable Objects
    const id = this.ctx.exports.StorageDO.idFromName('user-123');
    const stub = this.ctx.exports.StorageDO.get(id);
    mount('/mnt/user', stub);
  }
}

Implementing a WorkerFilesystem

Your entrypoint must implement the WorkerFilesystem interface. The interface is stream-first - you implement 6 core methods and higher-level operations like readFile/writeFile are automatically derived.

Here's a minimal in-memory example:

import { WorkerEntrypoint } from 'cloudflare:workers';
import type { WorkerFilesystem, Stat, DirEntry } from 'worker-fs-mount';

export class MemoryFS extends WorkerEntrypoint implements WorkerFilesystem {
  #files = new Map<string, Uint8Array>();
  #dirs = new Set<string>(['/']);

  async stat(path: string): Promise<Stat | null> {
    if (this.#dirs.has(path)) {
      return { type: 'directory', size: 0 };
    }
    const file = this.#files.get(path);
    if (!file) return null;
    return { type: 'file', size: file.length };
  }

  async createReadStream(path: string, options?: { start?: number; end?: number }): Promise<ReadableStream<Uint8Array>> {
    const file = this.#files.get(path);
    if (!file) throw new Error(`ENOENT: ${path}`);
    const start = options?.start ?? 0;
    const end = options?.end !== undefined ? options.end + 1 : file.length;
    const chunk = file.slice(start, end);
    return new ReadableStream({
      start(controller) {
        controller.enqueue(chunk);
        controller.close();
      },
    });
  }

  async createWriteStream(path: string, options?: { start?: number; flags?: 'w' | 'a' | 'r+' }): Promise<WritableStream<Uint8Array>> {
    const self = this;
    let offset = options?.start ?? 0;
    let content = options?.flags === 'a' || options?.flags === 'r+'
      ? (this.#files.get(path) ?? new Uint8Array(0))
      : new Uint8Array(0);
    if (options?.flags === 'a') offset = content.length;

    return new WritableStream({
      write(chunk) {
        const newLength = Math.max(content.length, offset + chunk.length);
        const newContent = new Uint8Array(newLength);
        newContent.set(content, 0);
        newContent.set(chunk, offset);
        content = newContent;
        offset += chunk.length;
        self.#files.set(path, content);
      },
    });
  }

  async readdir(path: string): Promise<DirEntry[]> {
    const prefix = path === '/' ? '/' : path + '/';
    const entries: DirEntry[] = [];
    const seen = new Set<string>();
    for (const [filePath] of this.#files) {
      if (filePath.startsWith(prefix)) {
        const name = filePath.slice(prefix.length).split('/')[0];
        if (name && !seen.has(name)) {
          seen.add(name);
          entries.push({ name, type: 'file' });
        }
      }
    }
    return entries;
  }

  async mkdir(path: string, options?: { recursive?: boolean }): Promise<string | undefined> {
    if (this.#dirs.has(path)) return undefined;
    this.#dirs.add(path);
    return path;
  }

  async rm(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {
    if (!this.#files.delete(path) && !this.#dirs.delete(path)) {
      if (!options?.force) throw new Error(`ENOENT: ${path}`);
    }
  }
}

For production implementations, see the r2-fs, durable-object-fs, and memory-fs packages.

API Reference

mount(path, stub): void

Mount a WorkerFilesystem at the specified path.

| Parameter | Type | Description | |-----------|------|-------------| | path | string | Mount point (must be absolute, start with /) | | stub | WorkerFilesystem | WorkerEntrypoint stub |

unmount(path): boolean

Unmount a filesystem at the specified path.

| Parameter | Type | Description | |-----------|------|-------------| | path | string | Mount point to unmount |

Returns true if a mount was removed, false if nothing was mounted at that path.

withMounts(fn): Promise<T>

Run a function with request-scoped mount isolation. Required for Durable Objects (getting a DO stub is IO). Use when different requests need different mounts (e.g., per-user DOs).

// Durable Objects require request scope - use withMounts for isolation
return withMounts(async () => {
  const userId = getUserId(request);
  const id = ctx.exports.UserStorage.idFromName(userId);
  mount('/user', ctx.exports.UserStorage.get(id));
  // Each request gets its own isolated mount
});

For R2, KV, service bindings, and same-worker entrypoints, prefer mounting at module level using import { env, exports } from 'cloudflare:workers'.

isMounted(path): boolean

Check if a path is under any mount.

isInMountContext(): boolean

Check if code is running inside a withMounts callback.

WorkerFilesystem Interface

The interface is stream-first with minimal required methods. Higher-level operations like readFile, writeFile, truncate, rename, cp, and unlink are automatically derived from these core methods.

Required Methods (6)

| Method | Description | |--------|-------------| | stat(path, options?) | Get file/directory metadata | | createReadStream(path, options?) | Create readable stream for a file | | createWriteStream(path, options?) | Create writable stream for a file | | readdir(path, options?) | List directory contents | | mkdir(path, options?) | Create directory | | rm(path, options?) | Remove file or directory |

Optional Methods (2)

| Method | Description | |--------|-------------| | symlink(linkPath, targetPath) | Create symlink | | readlink(path) | Read symlink target |

Automatically Derived Operations

These node:fs/promises methods are automatically implemented using the core streaming methods:

| Method | Derived From | |--------|--------------| | readFile | createReadStream | | writeFile | createWriteStream | | appendFile | createWriteStream with append flag | | truncate | createReadStream + createWriteStream | | unlink | stat + rm | | copyFile, cp | createReadStream + createWriteStream | | rename | streams + rm | | access | stat |

Supported fs Operations

The following node:fs/promises methods are intercepted:

  • readFile, writeFile, appendFile
  • stat, lstat
  • readdir
  • mkdir, rmdir, rm
  • unlink
  • rename
  • copyFile, cp
  • access
  • truncate
  • symlink, readlink
  • realpath
  • utimes

Synchronous Filesystem (Durable Objects)

When running inside a Durable Object, you can use synchronous filesystem operations by mounting a LocalDOFilesystem. This works because DO's ctx.storage.sql is synchronous within the DO context.

Setup

First, add the node:fs alias to your wrangler.toml:

[alias]
"node:fs/promises" = "worker-fs-mount/fs"
"node:fs" = "worker-fs-mount/fs-sync"

Then use LocalDOFilesystem inside your Durable Object:

import { DurableObject } from 'cloudflare:workers';
import { mount } from 'worker-fs-mount';
import { LocalDOFilesystem } from 'durable-object-fs';
import fs from 'node:fs';  // Aliased to worker-fs-mount/fs-sync

export class MyDO extends DurableObject {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    // Create and mount once in constructor - DOs are single-threaded
    const localFs = new LocalDOFilesystem(ctx.storage.sql);
    mount('/data', localFs);
  }

  fetch(request: Request): Response {
    // Synchronous fs operations work!
    const configExists = fs.existsSync('/data/config.json');

    if (!configExists) {
      fs.mkdirSync('/data', { recursive: true });
      fs.writeFileSync('/data/config.json', JSON.stringify({ initialized: true }));
    }

    const config = fs.readFileSync('/data/config.json', 'utf8');
    fs.writeFileSync('/data/output.txt', 'processed');

    const entries = fs.readdirSync('/data');

    return Response.json({ config: JSON.parse(config), entries });
  }
}

Unified Mount API

The mount() function accepts both async (WorkerFilesystem) and sync (SyncWorkerFilesystem) filesystems:

// Async filesystem (WorkerEntrypoint via jsrpc)
mount('/mnt/remote', env.STORAGE_SERVICE);

// Sync filesystem (LocalDOFilesystem inside DO)
mount('/data', new LocalDOFilesystem(ctx.storage.sql));

When using async fs.promises methods with a sync-only mount, they automatically fall back to the sync methods:

import fs from 'node:fs/promises';

// Even with sync-only LocalDOFilesystem, async methods work
await fs.readFile('/data/file.txt');  // Falls back to readFileSync internally

SyncWorkerFilesystem Interface

To create a sync filesystem, implement SyncWorkerFilesystem:

import type { SyncWorkerFilesystem, Stat, DirEntry } from 'worker-fs-mount';

class MySyncFs implements SyncWorkerFilesystem {
  statSync(path: string, options?: { followSymlinks?: boolean }): Stat | null { /* ... */ }
  readFileSync(path: string): Uint8Array { /* ... */ }
  writeFileSync(path: string, data: Uint8Array, options?: { flags?: 'w' | 'a' | 'r+' }): void { /* ... */ }
  readdirSync(path: string, options?: { recursive?: boolean }): DirEntry[] { /* ... */ }
  mkdirSync(path: string, options?: { recursive?: boolean }): string | undefined { /* ... */ }
  rmSync(path: string, options?: { recursive?: boolean; force?: boolean }): void { /* ... */ }
  // Optional:
  symlinkSync?(linkPath: string, targetPath: string): void;
  readlinkSync?(path: string): string;
}

Important Notes

  • DO Context Only: LocalDOFilesystem only works inside a Durable Object where ctx.storage.sql is available
  • Not a WorkerEntrypoint: LocalDOFilesystem operates directly on SQLite storage - it's not accessible via jsrpc
  • No withMounts needed: DOs are single-threaded, so mount once in the constructor - no request isolation required
  • Use wrangler alias: Import node:fs with the alias configured for best developer experience
  • Strong Consistency: DO serialization ensures single-threaded execution with no conflicts

Constraints

Sync Operations Require Sync Filesystem

Synchronous node:fs methods only work with filesystems that implement SyncWorkerFilesystem (like LocalDOFilesystem). Using sync methods on async-only mounts throws ENOSYS.

No File Descriptors

The fd-based API (open/read/write/close) is not supported. Use the high-level methods instead.

Same-Mount Operations

rename only works within the same mount. Cross-mount rename throws EXDEV. For cross-mount moves, use copyFile + unlink.

Reserved Paths

Cannot mount over /bundle, /tmp, or /dev.

No Nested Mounts

Cannot mount /mnt/a/b if /mnt/a is already mounted, or vice versa.

Error Handling

Errors follow Node.js conventions with .code property:

| Code | Meaning | |------|---------| | ENOENT | File or directory not found | | EEXIST | File already exists | | ENOTDIR | Expected directory but found file | | EISDIR | Expected file but found directory | | ENOSYS | Operation not supported by filesystem | | EXDEV | Cross-mount operation not supported | | EACCES | Permission denied |

Concurrency

The mounted WorkerFilesystem is responsible for handling concurrent access. For consistent state, use Durable Objects which provide single-threaded execution:

export class StorageDO extends DurableObject implements WorkerFilesystem {
  // All methods automatically serialized by DO runtime
}

License

MIT