Skip to content

Commit

Permalink
feat: add overwrite for write method
Browse files Browse the repository at this point in the history
  • Loading branch information
hughfenghen committed May 17, 2024
1 parent 6aff086 commit 63a89d0
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
4 changes: 3 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ export declare function file(filePath: string): OPFSFileWrap;
* // Write content to a file
await write('/path/to/file.txt', 'Hello, world!');
*/
export declare function write(target: string | OPFSFileWrap, content: string | BufferSource | ReadableStream<BufferSource> | OPFSFileWrap): Promise<void>;
export declare function write(target: string | OPFSFileWrap, content: string | BufferSource | ReadableStream<BufferSource> | OPFSFileWrap, opts?: {
overwrite: boolean;
}): Promise<void>;
/**
* Represents a wrapper for interacting with a file in the filesystem.
*/
Expand Down
13 changes: 13 additions & 0 deletions src/__tests__/file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@ test('write string to file', async () => {
expect(await file(filePath).text()).toBe('bar');
});

test('append data to file', async () => {
const f1 = file(filePath);
await write(f1, 'foo');
expect(await f1.text()).toBe('foo');

const f2 = file('/unit-test/file2');
await write(f2, 'bar');

await write(f1, f2, { overwrite: false });
await f2.remove();
expect(await f1.text()).toBe('foobar');
});

test('write stream to file', async () => {
await write(
filePath,
Expand Down
7 changes: 4 additions & 3 deletions src/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,11 @@ export function file(filePath: string) {
*/
export async function write(
target: string | OPFSFileWrap,
content: string | BufferSource | ReadableStream<BufferSource> | OPFSFileWrap
content: string | BufferSource | ReadableStream<BufferSource> | OPFSFileWrap,
opts = { overwrite: true }
) {
if (content instanceof OPFSFileWrap) {
await write(target, await content.stream());
await write(target, await content.stream(), opts);
return;
}

Expand All @@ -50,7 +51,7 @@ export async function write(
: file(target)
).createWriter();
try {
await writer.truncate(0);
if (opts.overwrite) await writer.truncate(0);
if (content instanceof ReadableStream) {
const reader = content.getReader();
while (true) {
Expand Down

0 comments on commit 63a89d0

Please sign in to comment.