Skip to content

Commit

Permalink
fix wrong truncation on fs.writeFileSync with fd argument (#10225)
Browse files Browse the repository at this point in the history
* fix wrong truncate

* close fd in test

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
  • Loading branch information
2 people authored and cirospaciari committed Apr 14, 2024
1 parent 5be46fa commit efb9c33
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/bun.js/node/node_fs.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5474,7 +5474,9 @@ pub const NodeFS = struct {
}
} else {
// https://github.com/oven-sh/bun/issues/2931
if ((@intFromEnum(args.flag) & std.os.O.APPEND) == 0) {
// https://github.com/oven-sh/bun/issues/10222
// only truncate if we're not appending and writing to a path
if ((@intFromEnum(args.flag) & std.os.O.APPEND) == 0 and args.file != .fd) {
_ = ftruncateSync(.{ .fd = fd, .len = @as(JSC.WebCore.Blob.SizeType, @truncate(written)) });
}
}
Expand Down
10 changes: 10 additions & 0 deletions test/js/node/fs/fs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2971,3 +2971,13 @@ describe.if(isWindows)("windows path handling", () => {
});
}
});

it("using writeFile on an fd does not truncate it", () => {
const temp = tmpdir();
const fd = fs.openSync(join(temp, "file.txt"), "w+");
fs.writeFileSync(fd, "x");
fs.writeFileSync(fd, "x");
fs.closeSync(fd);
const content = fs.readFileSync(join(temp, "file.txt"), "utf8");
expect(content).toBe("xx");
});

0 comments on commit efb9c33

Please sign in to comment.