diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index 44e8d040fd7b..5190767ccc08 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -571,20 +571,28 @@ function writevAll(chunks, size, pos, cb, retries = 0) { }); } +// FileSink.write(string) always emits UTF-8, so count that (not the caller's encoding). +function bytesForWrite(data: any): number { + return typeof data === "string" ? Buffer.byteLength(data) : (data?.byteLength ?? 0); +} + function _write(data, encoding, cb) { const fileSink = this[kWriteStreamFastPath]; if (fileSink && fileSink !== true) { + const bytes = bytesForWrite(data); const maybePromise = fileSink.write(data); if ($isPromise(maybePromise)) { maybePromise .then(() => { + this.bytesWritten += bytes; this.emit("drain"); // Emit drain event cb(null); }) .catch(cb); return false; // Indicate backpressure } else { + this.bytesWritten += bytes; cb(null); return true; // No backpressure } @@ -620,10 +628,12 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) this.fd = fileSink._getFd(); } + const bytes = bytesForWrite(data); const maybePromise = fileSink.write(data); if ($isPromise(maybePromise)) { maybePromise.then( () => { + this.bytesWritten += bytes; if (cb) cb(null); this.emit("drain"); }, @@ -634,6 +644,7 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) ); return false; } else { + this.bytesWritten += bytes; if (cb) process.nextTick(cb, null); return true; } @@ -667,12 +678,14 @@ function writeFast(this: FSStream, data: any, encoding: any, cb: any) { const fileSink = this[kWriteStreamFastPath]; if (fileSink && fileSink !== true) { + const bytes = bytesForWrite(data); const maybePromise = fileSink.write(data); if ($isPromise(maybePromise)) { // Two-arg then(): a throw from the fulfillment handler must not be // mistaken for a write failure. maybePromise.then( () => { + this.bytesWritten += bytes; this.emit("drain"); // Emit drain event cb(null); }, @@ -685,6 +698,7 @@ function writeFast(this: FSStream, data: any, encoding: any, cb: any) { ); return false; // Indicate backpressure } else { + this.bytesWritten += bytes; cb(null); return true; // No backpressure } @@ -712,16 +726,19 @@ writeStreamPrototype._writev = function (data, cb) { const fileSink = this[kWriteStreamFastPath]; if (fileSink && fileSink !== true) { - const maybePromise = fileSink.write(Buffer.concat(chunks)); + const buffer = Buffer.concat(chunks); + const maybePromise = fileSink.write(buffer); if ($isPromise(maybePromise)) { maybePromise .then(() => { + this.bytesWritten += buffer.length; this.emit("drain"); cb(null); }) .catch(cb); return false; } else { + this.bytesWritten += buffer.length; cb(null); return true; } diff --git a/test/js/node/process/process-stdio.test.ts b/test/js/node/process/process-stdio.test.ts index ba35bc4f0484..6642272a12ae 100644 --- a/test/js/node/process/process-stdio.test.ts +++ b/test/js/node/process/process-stdio.test.ts @@ -1,6 +1,7 @@ import { spawn, spawnSync } from "bun"; import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe } from "harness"; +import { bunEnv, bunExe, isWindows, tempDir } from "harness"; +import { readFileSync } from "node:fs"; import path from "path"; import { isatty } from "tty"; describe.concurrent("process-stdio", () => { @@ -158,4 +159,94 @@ describe.concurrent("process-stdio", () => { `hello worldhello again|😋 Get Emoji — All Emojis to ✂️ Copy and 📋 Paste 👌`.repeat(9999), ); }); + + // #23061: the FileSink fast path used for stdio handed chunks straight to the + // sink without touching this.bytesWritten, so the counter stayed at 0. Node + // (net.Socket/tty.WriteStream) reports the encoded byte count synchronously. + test("process.stdout/stderr.bytesWritten tracks fast-path writes", async () => { + using dir = tempDir("stdio-bytes-written", {}); + const reportPath = path.join(String(dir), "report.json"); + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const fs = require("node:fs"); + const before = { stdout: process.stdout.bytesWritten, stderr: process.stderr.bytesWritten }; + process.stdout.write("out-🚀"); // 8 UTF-8 bytes (4 + 4) + process.stdout.write(Buffer.from([65, 66])); // 2 bytes -> stdout total 10 + process.stderr.write("err-⚡"); // 7 UTF-8 bytes (4 + 3) + fs.writeFileSync(${JSON.stringify(reportPath)}, JSON.stringify({ + before, + stdout: process.stdout.bytesWritten, + stderr: process.stderr.bytesWritten, + })); + `, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + + expect(stdout).toBe("out-🚀AB"); + expect(stderr).toBe("err-⚡"); + expect(JSON.parse(readFileSync(reportPath, "utf8"))).toEqual({ + before: { stdout: 0, stderr: 0 }, + stdout: 10, + stderr: 7, + }); + expect(exitCode).toBe(0); + }); + + // A write that the sink rejects (EPIPE) must not bump the counter. Node's + // net.Socket only adds to _bytesDispatched after a successful low-level + // write, so bytesWritten stays at whatever the last successful write left it. + test.skipIf(isWindows)("process.stdout.bytesWritten does not count a rejected write", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + process.stdout.on("error", () => {}); + process.stdout.write("abc"); + process.stderr.write("after-ok:" + process.stdout.bytesWritten + "\\n"); + process.stdin.once("data", () => { + process.stdout.write("xxxxxxxxxxxx", err => { + process.stderr.write(JSON.stringify({ + errored: err != null, + bytesWritten: process.stdout.bytesWritten, + }) + "\\n"); + process.exit(0); + }); + }); + process.stdin.resume(); + `, + ], + env: bunEnv, + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + }); + + // Drain the child's first write so "abc" is out of the pipe buffer, then + // close the read end so the child's next stdout write fails with EPIPE. + const reader = proc.stdout.getReader(); + let seen = 0; + while (seen < 3) { + const { value, done } = await reader.read(); + if (done) break; + seen += value!.length; + } + await reader.cancel(); + + proc.stdin.write("go\n"); + proc.stdin.flush(); + + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + const lines = stderr.trim().split("\n"); + expect(lines[0]).toBe("after-ok:3"); + expect(JSON.parse(lines[1])).toEqual({ errored: true, bytesWritten: 3 }); + expect(exitCode).toBe(0); + }); });