Skip to content

Commit 506c275

Browse files
authored
fix(ext/fs): truncate files when a ReadableStream is passed to writeFile (#23330)
Closes #19697. This fixes a bug where the writeFile API can create partially-overwritten files which may lead to invalid / corrupt files or data leakage. It also aligns the behavior of writing a ReadableStream and writing a Uint8Array to the disk.
1 parent 35e5159 commit 506c275

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

ext/fs/30_fs.js

+1
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,7 @@ async function writeFile(
926926
append: options.append ?? false,
927927
create: options.create ?? true,
928928
createNew: options.createNew ?? false,
929+
truncate: !(options.append ?? false),
929930
write: true,
930931
});
931932
await data.pipeTo(file.writable, {

tests/unit/write_file_test.ts

+18
Original file line numberDiff line numberDiff line change
@@ -425,3 +425,21 @@ Deno.test(
425425
assertEquals(Deno.readFileSync(filename), new Uint8Array([1, 2]));
426426
},
427427
);
428+
429+
Deno.test(
430+
{ permissions: { read: true, write: true } },
431+
async function overwriteFileWithStream() {
432+
const filename = Deno.makeTempDirSync() + "/test.txt";
433+
await Deno.writeFile(filename, new Uint8Array([1, 2, 3, 4]));
434+
435+
const stream = new ReadableStream({
436+
pull(controller) {
437+
controller.enqueue(new Uint8Array([1]));
438+
controller.enqueue(new Uint8Array([2]));
439+
controller.close();
440+
},
441+
});
442+
await Deno.writeFile(filename, stream);
443+
assertEquals(Deno.readFileSync(filename), new Uint8Array([1, 2]));
444+
},
445+
);

0 commit comments

Comments
 (0)