From c89e7429f74e6fe47d77e3b8482fcfb1e888e9f3 Mon Sep 17 00:00:00 2001 From: Vanilagy <1696106+Vanilagy@users.noreply.github.com> Date: Mon, 27 Apr 2026 18:29:52 +0200 Subject: [PATCH] Fix FilePathSource/FilePathTarget not working in server-side environments using CJS (closes #360) --- scripts/bundle.ts | 1 + src/node.ts | 3 ++- src/source.ts | 4 ++-- src/target.ts | 8 +++++++- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/scripts/bundle.ts b/scripts/bundle.ts index 7dcc1ae..e5f9063 100644 --- a/scripts/bundle.ts +++ b/scripts/bundle.ts @@ -30,6 +30,7 @@ const createVariants = async ( */`, }, legalComments: 'none', + platform: 'node', }; const umdConfig: esbuild.BuildOptions = { diff --git a/src/node.ts b/src/node.ts index 3ed1aa3..4718ebc 100644 --- a/src/node.ts +++ b/src/node.ts @@ -8,4 +8,5 @@ // This file contains Node.js-specific code that does not run in a browser. -export * as fs from 'node:fs/promises'; +// Dynamic import so it can be included in the bundles and still work properly in the browser +export const getFs = () => import('node:fs/promises'); diff --git a/src/source.ts b/src/source.ts index 7e2d298..553c8e6 100644 --- a/src/source.ts +++ b/src/source.ts @@ -959,7 +959,7 @@ export class FilePathSource extends PathedSource { throw new TypeError('options.maxCacheSize, when provided, must be a non-negative number.'); } - if (!node.fs) { + if (!node.getFs) { throw new Error( 'FilePathSource is only available in server-side environments (Node.js, Bun, Deno).', ); @@ -970,7 +970,7 @@ export class FilePathSource extends PathedSource { // Let's back this source with a StreamSource, makes the implementation very simple this._streamSource = new StreamSource({ getSize: async () => { - this._fileHandle = await node.fs.open(filePath, 'r'); + this._fileHandle = await (await node.getFs()).open(filePath, 'r'); const stats = await this._fileHandle.stat(); return stats.size; diff --git a/src/target.ts b/src/target.ts index 20a6aeb..ec44613 100644 --- a/src/target.ts +++ b/src/target.ts @@ -692,12 +692,18 @@ export class FilePathTarget extends Target { throw new TypeError('options must be an object.'); } + if (!node.getFs) { + throw new Error( + 'FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).', + ); + } + super(); // Let's back this target with a StreamTarget, makes the implementation very simple const writable = new WritableStream({ start: async () => { - this._fileHandle = await node.fs.open(filePath, 'w'); + this._fileHandle = await (await node.getFs()).open(filePath, 'w'); }, write: async (chunk) => { assert(this._fileHandle);