Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ext/fs): truncate files when a ReadableStream is passed to writeFile #23330

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions ext/fs/30_fs.js
Expand Up @@ -926,6 +926,7 @@ async function writeFile(
append: options.append ?? false,
create: options.create ?? true,
createNew: options.createNew ?? false,
truncate: true,
char marked this conversation as resolved.
Show resolved Hide resolved
write: true,
});
await data.pipeTo(file.writable, {
Expand Down
18 changes: 18 additions & 0 deletions tests/unit/write_file_test.ts
Expand Up @@ -425,3 +425,21 @@ Deno.test(
assertEquals(Deno.readFileSync(filename), new Uint8Array([1, 2]));
},
);

Deno.test(
{ permissions: { read: true, write: true } },
async function overwriteFileWithStream() {
const filename = Deno.makeTempDirSync() + "/test.txt";
await Deno.writeFile(filename, new Uint8Array([1, 2, 3, 4]));

const stream = new ReadableStream({
pull(controller) {
controller.enqueue(new Uint8Array([1]));
controller.enqueue(new Uint8Array([2]));
controller.close();
},
});
Copy link

Choose a reason for hiding this comment

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

Suggested change
});
});
// append not set should overwrite

await Deno.writeFile(filename, stream);
assertEquals(Deno.readFileSync(filename), new Uint8Array([1, 2]));
},
Copy link

Choose a reason for hiding this comment

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

Suggested change
},
// append false should also overwrite
await Deno.writeFile(filename, new Response(new Uint8Array([1, 2, 3])).body!, {append: false});
assertEquals(Deno.readFileSync(filename), new Uint8Array([1, 2, 3]));
// append set should append
await Deno.writeFile(filename, new Response(new Uint8Array([4, 5])).body!, {append: true});
assertEquals(Deno.readFileSync(filename), new Uint8Array([1, 2, 3, 4, 5]));
},

);