Skip to content

fs.promises: accept iterable data in appendFile, like writeFile and node - #39186

Closed
robobun wants to merge 3 commits into
mainfrom
farm/96483f7c/promises-appendfile-iterable
Closed

robobun wants to merge 3 commits into
mainfrom
farm/96483f7c/promises-appendfile-iterable

Conversation

@robobun

@robobun robobun commented Aug 15, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • fs.promises.appendFile(path, ["a", "b"]) (or a String object, a generator, a Readable) rejects with ERR_INVALID_ARG_TYPE: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Node v26 appends ab; fs.promises.writeFile with the same data already works in Bun.
  • Cause: exports.appendFile in src/js/node/fs.promises.ts:252 hands data straight to the native binding, whose args::WriteFile::from_js (src/runtime/node/node_fs.rs:4220) only takes strings and buffers. Only exports.writeFile (fs.promises.ts:312) has the branch that sends iterables to writeFileAsyncIterator.
  • Two more defects in that shared iterable path, both of which appendFile would inherit:
    • It only opened string paths itself (mustClose = typeof fdOrPath === "string", fs.promises.ts:1628). A Buffer or URL path went to Bun.file(path).writer(), which ignores flag and mode and overwrites in place: promises.writeFile(new URL(...), ["ZZ"]) on a file holding 0123456789 leaves ZZ23456789, { flag: "a" } does not append, { flag: "wx" } does not fail on an existing file.
    • After writing, it ran ftruncate(fd, totalBytesWritten) (fs.promises.ts:1654), where the total is the sum of the FileSink.write() return values. That sum over-counts once the sink starts flushing, so promises.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, and appendFile(..., { 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.appendFile sends iterable data through writeFileAsyncIterator with "a" as the default flag; exports.writeFile passes "w". The iterable test moves into a shared isCustomIterable (same predicate as node's: iterable, not an ArrayBufferView, not a string). String and buffer data still take the native path, and appendFileSync / callback appendFile are unchanged: node rejects iterables there too.
  • writeFileAsyncIterator opens anything that is not already an fd with fs.open(path, flag, mode), so string, Buffer and URL paths behave the same; fs.open rejects anything else with ERR_INVALID_ARG_TYPE. A FileHandle is unwrapped to its fd by the callers as before and is neither opened nor closed here.
  • The post-write ftruncate, the byte counter feeding it and the flagTruncates helper are removed. The flags it fired for (w, w+, wx, ...) all carry O_TRUNC (src/runtime/node/types.rs:1708), and on Windows the create disposition is derived from O_TRUNC too (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.
  • Two details made consistent while the function was restructured: an empty flag falls back to the default (node's options.flag || 'a' / || 'w', also what the native path does via a truthiness check), and an unknown encoding rejects with node's ERR_INVALID_ARG_VALUE instead of a plain TypeError, which is the code appendFile already produced for that input via the native path. The undocumented positional flag and mode arguments that only the iterable path of promises.writeFile read are gone; node and Bun's native path both ignore arguments past options.
  • Why this is right: node's fsPromises.appendFile is literally options.flag ||= 'a'; return writeFile(path, data, options), and its writeFile opens whatever path kind it gets and drains isCustomIterable(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.
  • Verified with 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 and mode; encoding as argument and option; explicit and empty flag; 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), and promises.writeFile and appendFile of many small chunks (32 x 1 KiB chunks through writeFile, appendFile with flag: "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.
  • Also run: the rest of fs.test.ts, fs-promises-writeFile-async-iterator.test.ts, promises.test.js (580 pass across the three files), and node's test-fs-append-file*, test-fs-promises-file-handle-append-file, test-fs-promises-file-handle-writeFile, test-fs-promises-writefile*.
  • Not changed here: the iterable path still ignores { 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 through Bun.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 / appendFile in 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 to writeFileAsyncIterator in fs.promises.ts, which opens the path with fs.open, drains the iterable into Bun.file(fd).writer() (a FileSink), and closes the fd. FileHandle#writeFile and FileHandle#appendFile call exports.writeFile with the handle's fd, so they already reached the iterable path.
  • FileSink buffers 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 removed ftruncate was the only consumer of that sum.
  • In node, data for the promise versions is documented as string | Buffer | TypedArray | DataView | AsyncIterable | Iterable | Stream; each chunk is written in order (a string chunk is encoded with the encoding option). A String object qualifies because it is iterable (one chunk per character). The sync and callback versions take only strings and buffers.
  • fs.open here is the promise-returning native binding; it accepts string, Buffer and URL paths, honors flag and mode, and throws ERR_INVALID_ARG_TYPE for 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)
promises.appendFile(path, array of strings):   bun: ERR_INVALID_ARG_TYPE    node: "0ab"
promises.appendFile(path, String wrapper):     bun: ERR_INVALID_ARG_TYPE    node: "0ab"
promises.appendFile(path, array of buffers):   bun: ERR_INVALID_ARG_TYPE    node: "0ab"
promises.appendFile(path, Set):                bun: ERR_INVALID_ARG_TYPE    node: "0ab"
promises.appendFile(path, async generator):    bun: ERR_INVALID_ARG_TYPE    node: "0xyz"
promises.appendFile(path, Readable):           bun: ERR_INVALID_ARG_TYPE    node: "0ab"
promises.appendFile(path, []):                 bun: ERR_INVALID_ARG_TYPE    node: "0"
promises.appendFile(path, ['é'], 'latin1'):    bun: ERR_INVALID_ARG_TYPE    node: [0x30, 0xe9]
promises.appendFile(path, ['a'], {flag:'w'}):  bun: ERR_INVALID_ARG_TYPE    node: "a"
promises.appendFile(missing, ['a'], {mode:0o600}): bun: ERR_INVALID_ARG_TYPE  node: mode 600
promises.appendFile(path, ['a'], {signal: aborted}): bun: ERR_INVALID_ARG_TYPE  node: AbortError
promises.appendFile(Buffer path, ['a','b']):   bun: ERR_INVALID_ARG_TYPE    node: "0ab"
promises.appendFile(URL path, ['a','b']):      bun: ERR_INVALID_ARG_TYPE    node: "0ab"
promises.appendFile(FileHandle, ['a','b']):    bun: ERR_INVALID_ARG_TYPE    node: "0ab"
FileHandle#appendFile(['a','b']):              bun: "0ab"                   node: "0ab"
fs.appendFileSync(path, ['a','b']):            bun: ERR_INVALID_ARG_TYPE    node: ERR_INVALID_ARG_TYPE
fs.appendFile(path, ['a','b'], cb):            bun: ERR_INVALID_ARG_TYPE    node: ERR_INVALID_ARG_TYPE

file held "0123" before each of these; data is ["a"] (or ["a", "b"] for the flag 'a' rows):
promises.writeFile(Buffer path, iterable, {flag:'a'}):   bun: "ab23"       node: "0123ab"
promises.writeFile(URL path, iterable, {flag:'a'}):      bun: "ab23"       node: "0123ab"
promises.writeFile(Buffer path, iterable, {flag:'wx'}):  bun: "a123"       node: EEXIST
promises.writeFile(URL path, iterable, {flag:'r'}):      bun: "a123"       node: EBADF
promises.writeFile(missing URL, iterable, {mode:0o600}): bun: mode 644     node: mode 600
promises.writeFile(string path, ...same four...):        bun: matches node already

resulting file size for 500 x "0123456789" (node: 5000 for every row)
                                  bun 1.4.0   first fix only   this branch
promises.writeFile(string)        9090        9090             5000
promises.writeFile(Buffer)        5000        9090             5000
promises.writeFile(URL)           5000        9090             5000
promises.appendFile(string)       throws      5000             5000
promises.appendFile({flag:'w'})   throws      9090             5000
promises.appendFile(Buffer)       throws      5000             5000

…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.
@coderabbitai

coderabbitai Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

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.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: bcc9f9de-9707-4d8f-8bf0-2ff51fa40436

📥 Commits

Reviewing files that changed from the base of the PR and between c19cab4 and 343bab4.

📒 Files selected for processing (2)
  • src/js/node/fs.promises.ts
  • test/js/node/fs/fs.test.ts

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Aug 15, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 5:07 PM PT - Aug 15th, 2026

✅ @robobun, your commit 343bab4b4a993ae7615a823d431e00e51f11ec4e passed in Build #98820! 🎉


🧪   To try this PR locally:

bunx bun-pr 39186

That installs a local version of the PR into your bun-39186 executable, so you can run:

bun-39186 --bun

@robobun

robobun commented Aug 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

  • Reproduced on the released build (USE_SYSTEM_BUN=1): fs.promises.appendFile(path, ["a", "b"]) and appendFile(path, new String("ab")) reject with ERR_INVALID_ARG_TYPE; node v26.3.0 writes ab for both, and fs.promises.writeFile with the same data already works in Bun.
  • Fix is in this PR. Self-review turned up that routing Buffer/URL paths (and appendFile with flag: "w") through the shared iterable path would have given them the NUL padding bug that string paths already had (fs.promises.writeFile: stop appending NUL tail when writing a stream/async-iterable #35513), so the post-write ftruncate is removed here too, with exact-size tests for every path kind; details in the description.
  • 32 of the 37 new cases in test/js/node/fs/fs.test.ts fail on the released build and pass with this branch; the rest of fs.test.ts, fs-promises-writeFile-async-iterator.test.ts, promises.test.js and node's test-fs-append-file* / test-fs-promises-writefile* / test-fs-promises-file-handle-{append-file,writeFile} tests still pass.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • isCustomIterable is the same predicate previously inlined in writeFile, now shared; string/buffer data still hits the native binding.
  • mustClose = typeof fdOrPath !== "number" is safe because both callers unwrap FileHandle to its fd first; flagTruncates("a") is false so append never ftruncates.
  • Dropping the undocumented positional flag/mode args aligns with node and the native path (both ignore args past options).
  • 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.

@robobun

robobun commented Aug 15, 2026

Copy link
Copy Markdown
Collaborator Author

Cross-reference: #39192 adds the options.flush validation and fsync to writeFileAsyncIterator that this PR's description leaves out of scope. It contains the same one-line mustClose = typeof fdOrPath !== "number" change (with the same comment text) and does not touch anything else this PR changes, so whichever of the two lands second only has to drop that hunk on rebase.

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.
Comment thread src/js/node/fs.promises.ts Resolved
Comment thread src/js/node/fs.promises.ts Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • isCustomIterable is 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.open rejects invalid path types.
  • flagTruncates had no other callers; the w/w+/wx flags carry O_TRUNC at open, and the removed byte counter was the only consumer of the over-counted sum.
  • null options still works via optional chaining; empty flag falls back like Node's ||; the dropped positional flag/mode args 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 flagTruncates and writeFileAsyncIterator have no other callers; dead code is fully removed.
  • The dropped positional flag/mode parameters on writeFileAsyncIterator were only reachable via the old ...args spread from writeFile, which Node's 3-arg signature never populates.
  • typeof null === "object" sends a null options 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). The mode: 0o600 assertion is umask-safe.
  • The comment-cop bot's two flags were addressed in 343bab4 (comments cut to one line each).

@github-actions

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

@github-actions github-actions Bot closed this Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant