Repository navigation
Conversation
…paths on the iterable path fs.promises.appendFile passed every kind of data to the native binding, which only takes strings and buffers, so arrays, String objects, generators and streams were rejected with ERR_INVALID_ARG_TYPE while fs.promises.writeFile and node accept them. Route them through the same iterable path as writeFile, with 'a' as the default flag. That path only opened string paths itself; a Buffer or URL path went to Bun.file().writer(), which ignores flag and mode and overwrites the file in place. Open every non-fd argument with fs.open instead. An unknown encoding on this path now rejects with ERR_INVALID_ARG_VALUE like the string path does, and an empty flag falls back to the default as in node.
|
Warning Review limit reached
Next review available in: 22 minutes Limit details: You’ve used all 5 included reviews currently available under your plan. Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
Comment |
|
Updated 5:07 PM PT - Aug 15th, 2026
✅ @robobun, your commit 343bab4b4a993ae7615a823d431e00e51f11ec4e passed in 🧪 To try this PR locally: bunx bun-pr 39186That installs a local version of the PR into your bun-39186 --bun |
|
Status
|
There was a problem hiding this comment.
LGTM — focused Node compat fix that routes iterable data in fs.promises.appendFile through the same path writeFile already uses, and fixes the shared iterable path to open Buffer/URL paths with fs.open so flag/mode are honored.
What was reviewed:
isCustomIterableis the same predicate previously inlined inwriteFile, now shared; string/buffer data still hits the native binding.mustClose = typeof fdOrPath !== "number"is safe because both callers unwrapFileHandleto its fd first;flagTruncates("a")is false so append never ftruncates.- Dropping the undocumented positional
flag/modeargs aligns with node and the native path (both ignore args pastoptions). - 28 new tests cover the variant matrix (iterable kinds, path kinds, flag/mode/encoding, abort, error propagation, fd-leak check, negative cases for sync/callback forms).
Extended reasoning...
Overview
Two files touched: src/js/node/fs.promises.ts (JS-side Node compat shim, ~40 lines net) and test/js/node/fs/fs.test.ts (+237 lines, two new describe blocks with 28 cases). The runtime change extracts the iterable-data predicate into isCustomIterable, adds it to exports.appendFile with default flag "a", and restructures writeFileAsyncIterator to (a) take a defaultFlag parameter, (b) open any non-number path via fs.open instead of only strings, (c) use || for options.flag fallback like node, and (d) throw ERR_INVALID_ARG_VALUE for a bad encoding instead of a plain TypeError. The undocumented positional flag/mode parameters (previously reached only via the writeFile spread) are removed.
Security risks
None. This is the node:fs/promises compat layer; the change delegates path validation to the existing fs.open native binding, which already rejects non-path values with ERR_INVALID_ARG_TYPE. No new input parsing, no shell/exec, no auth/crypto surface.
Level of scrutiny
Medium — Node compat behavior change in a built-in module, but confined to the JS shim and directly mirroring node's own implementation (appendFile in node is options.flag ||= 'a'; return writeFile(...)). No native code, no memory management, no GC concerns. The one semantic widening (mustClose now covers Buffer/URL paths) is a bug fix with its own test block, and the FileHandle case is unaffected because both callers unwrap to a numeric fd before calling writeFileAsyncIterator. I traced flagTruncates to confirm the post-write truncate does not fire for append flags.
Other factors
Test coverage is thorough per the repo's variant-matrix guidance: every iterable kind (array, String object, buffers, sync/async generator, Readable), every path kind (string, Buffer, URL, FileHandle), encoding as arg and option, explicit/empty flag, mode, pre-aborted signal, iterable throwing mid-stream, an fd-leak check across 32 opens using the existing getMaxFD() pattern, and negative guards that non-iterable data and the sync/callback forms still reject. The PR description includes a node v26.3.0 probe table showing every changed row now matches node. The removed positional args were undocumented and diverged from both node and Bun's own native path, so dropping them is a compat improvement, not a regression.
|
Cross-reference: #39192 adds the |
The iterable path resized the file to the sum of the FileSink.write() return values after writing. That sum over-counts once the sink starts flushing, so a stream of small chunks came out padded with NUL bytes (same change as #35513). Now that Buffer and URL paths and appendFile with a truncating flag go through this path too, every one of them would have inherited the padding. The truncating flags already empty the file at open, so nothing needs resizing afterwards.
There was a problem hiding this comment.
I reviewed this and didn't find any bugs. It bundles three interacting behavioral changes to fs.promises.writeFile/appendFile (iterable routing for appendFile, opening Buffer/URL paths via fs.open, and dropping the post-write ftruncate), so a human look is still worthwhile before it lands.
What was reviewed:
isCustomIterableis the same predicate writeFile already used; strings/typed arrays still take the native path, and sync/callback forms are unchanged.mustClose = typeof fdOrPath !== "number": FileHandle is unwrapped to its fd by both callers before this runs, so it is not reopened or closed;fs.openrejects invalid path types.flagTruncateshad no other callers; thew/w+/wxflags carryO_TRUNCat open, and the removed byte counter was the only consumer of the over-counted sum.nulloptions still works via optional chaining; emptyflagfalls back like Node's||; the dropped positionalflag/modeargs were never reachable from the documented API.
Extended reasoning...
Overview
The PR touches src/js/node/fs.promises.ts (~60 changed lines) and adds ~270 lines of tests to test/js/node/fs/fs.test.ts. It makes fs.promises.appendFile accept iterable/async-iterable data by routing it through the existing writeFileAsyncIterator with default flag "a", extracts the iterable predicate into isCustomIterable, and fixes two pre-existing defects in that shared path: Buffer/URL paths now go through fs.open(path, flag, mode) instead of Bun.file(path).writer() (so flag/mode are honored), and the post-write ftruncate — which padded files with NULs because the byte total over-counted once the FileSink flushed — is removed along with the flagTruncates helper and the totalBytesWritten accumulator.
Security risks
None identified. No untrusted-input parsing, no path-traversal surface beyond what fs.open already validates, no crypto/auth. The change hands non-number paths to the native fs.open binding, which is the same validator the string-path case already used.
Level of scrutiny
Medium-high. This is core node:fs/promises compat surface that many packages exercise, and it removes a truncate step someone once added deliberately. The reasoning for each removal is well-argued and cross-referenced (O_TRUNC on open, Node's own appendFile being flag ||= 'a'; writeFile(...), the FileSink flush accounting), and 32 of the 37 new tests fail on the released build. Still, three interacting behavioral changes in one PR to a hot API, with the latest CI build showing as cancelled at review time, is more than I'd auto-approve.
Other factors
- Verified
flagTruncatesandwriteFileAsyncIteratorhave no other callers; dead code is fully removed. - The dropped positional
flag/modeparameters onwriteFileAsyncIteratorwere only reachable via the old...argsspread fromwriteFile, which Node's 3-arg signature never populates. typeof null === "object"sends anulloptions into the object branch, but every read is?.-guarded so it behaves as before.- Tests cover the variant matrix (path kinds × writers × flags, encoding as arg vs option, abort, iterator throw, fd-leak check, sync/callback still reject) and follow harness conventions (
tempDir,Buffer.alloc(...).toString(),it.each). Themode: 0o600assertion is umask-safe. - The comment-cop bot's two flags were addressed in 343bab4 (comments cut to one line each).
|
Closing this PR because it has been inactive for more than 90 days. |
Problem
fs.promises.appendFile(path, ["a", "b"])(or aStringobject, a generator, aReadable) rejects withERR_INVALID_ARG_TYPE: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Node v26 appendsab;fs.promises.writeFilewith the same data already works in Bun.exports.appendFileinsrc/js/node/fs.promises.ts:252handsdatastraight to the native binding, whoseargs::WriteFile::from_js(src/runtime/node/node_fs.rs:4220) only takes strings and buffers. Onlyexports.writeFile(fs.promises.ts:312) has the branch that sends iterables towriteFileAsyncIterator.stringpaths itself (mustClose = typeof fdOrPath === "string",fs.promises.ts:1628). ABufferorURLpath went toBun.file(path).writer(), which ignoresflagandmodeand overwrites in place:promises.writeFile(new URL(...), ["ZZ"])on a file holding0123456789leavesZZ23456789,{ flag: "a" }does not append,{ flag: "wx" }does not fail on an existing file.ftruncate(fd, totalBytesWritten)(fs.promises.ts:1654), where the total is the sum of theFileSink.write()return values. That sum over-counts once the sink starts flushing, sopromises.writeFile(path, 500 x "0123456789")produces a 9090 byte file (5000 bytes of data plus NUL padding) on a string path. The same bug and fix as fs.promises.writeFile: stop appending NUL tail when writing a stream/async-iterable #35513. Sending Buffer and URL paths, andappendFile(..., { flag: "w" }), through this code would have extended the padding to them (measured: 9090 bytes for all of them with only the first fix applied), so this PR removes the truncate as well.Fix
exports.appendFilesends iterable data throughwriteFileAsyncIteratorwith"a"as the default flag;exports.writeFilepasses"w". The iterable test moves into a sharedisCustomIterable(same predicate as node's: iterable, not anArrayBufferView, not a string). String and buffer data still take the native path, andappendFileSync/ callbackappendFileare unchanged: node rejects iterables there too.writeFileAsyncIteratoropens anything that is not already an fd withfs.open(path, flag, mode), so string,BufferandURLpaths behave the same;fs.openrejects anything else withERR_INVALID_ARG_TYPE. AFileHandleis unwrapped to its fd by the callers as before and is neither opened nor closed here.ftruncate, the byte counter feeding it and theflagTruncateshelper are removed. The flags it fired for (w,w+,wx, ...) all carryO_TRUNC(src/runtime/node/types.rs:1708), and on Windows the create disposition is derived fromO_TRUNCtoo (src/sys/lib.rs:6997), so the file is empty when writing starts and ends up exactly as long as the data. Node does not truncate after writing on this path either.flagfalls back to the default (node'soptions.flag || 'a'/|| 'w', also what the native path does via a truthiness check), and an unknown encoding rejects with node'sERR_INVALID_ARG_VALUEinstead of a plainTypeError, which is the codeappendFilealready produced for that input via the native path. The undocumented positionalflagandmodearguments that only the iterable path ofpromises.writeFileread are gone; node and Bun's native path both ignore arguments pastoptions.fsPromises.appendFileis literallyoptions.flag ||= 'a'; return writeFile(path, data, options), and itswriteFileopens whatever path kind it gets and drainsisCustomIterable(data)into it without resizing afterwards. This makes appendFile the same thin wrapper over the same writer, and the writer itself behaves the same for every path kind.test/js/node/fs/fs.test.ts, 37 new cases in three groups:promises.appendFile with iterable data(array, String object, buffers, sync and async generators,Readable; file creation andmode; encoding as argument and option; explicit and emptyflag; Buffer and URL paths; FileHandle left open; pre-aborted signal; error from the iterable; fd count stable across 32 opens including failing ones; bad encoding; non-iterable data and the sync/callback forms still rejected),promises.writeFile with iterable data and a Buffer or URL path(truncation,flag: "a",flag: "wx",mode, invalid path rejected before iterating), andpromises.writeFile and appendFile of many small chunks(32 x 1 KiB chunks through writeFile, appendFile withflag: "w"and plain appendFile, each to a string, Buffer and URL path, asserting the exact contents; 32 KiB clears the sink's 16 KiB flush size on Apple Silicon). 32 of the 37 fail on the released build; the 5 that pass there guard behavior that must not change, and the Buffer/URL exact-size ones are the cases that failed with only the first fix applied.fs.test.ts,fs-promises-writeFile-async-iterator.test.ts,promises.test.js(580 pass across the three files), and node'stest-fs-append-file*,test-fs-promises-file-handle-append-file,test-fs-promises-file-handle-writeFile,test-fs-promises-writefile*.{ flush: true }(it did for writeFile before as well; fs.promises: validate options.flush for iterable data and FileHandles, sync like node #39192 adds it), it still drains throughBun.file(fd).writer()(fs.promises.writeFile: apply backpressure when draining an (async) iterable #35520 is about replacing that), and the per-chunk type error messages differ from node's wording as before.Background
fs.promises.writeFile/appendFilein Bun have two implementations. String and buffer data go to the native binding (_writeFile/_appendFile, Rust), which opens, writes and closes in one call. Iterable data goes towriteFileAsyncIteratorinfs.promises.ts, which opens the path withfs.open, drains the iterable intoBun.file(fd).writer()(aFileSink), and closes the fd.FileHandle#writeFileandFileHandle#appendFilecallexports.writeFilewith the handle's fd, so they already reached the iterable path.FileSinkbuffers small writes and flushes once the buffer reaches 4 KiB (16 KiB on Apple Silicon,src/io/PipeWriter.rs:650).write()returns the bytes a call pushed out, which on a flushing call includes bytes earlier calls already reported, so summing the return values over-counts. The removedftruncatewas the only consumer of that sum.datafor the promise versions is documented asstring | Buffer | TypedArray | DataView | AsyncIterable | Iterable | Stream; each chunk is written in order (a string chunk is encoded with theencodingoption). AStringobject qualifies because it is iterable (one chunk per character). The sync and callback versions take only strings and buffers.fs.openhere is the promise-returning native binding; it accepts string,BufferandURLpaths, honorsflagandmode, and throwsERR_INVALID_ARG_TYPEfor anything else, which is why every non-fd value can be handed to it.Probe against node v26.3.0 (released bun 1.4.0 on the left; this branch matches node on every line)