Skip to content

Commit

Permalink
feat: 🎸 add copyFile() method
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jun 20, 2023
1 parent c7e7e46 commit de2bb0a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
33 changes: 28 additions & 5 deletions src/fsa-to-node/FsaNodeFs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,11 +251,34 @@ export class FsaNodeFs implements FsCallbackApi, FsCommonObjects {
throw new Error('Not implemented');
}

copyFile(src: misc.PathLike, dest: misc.PathLike, callback: misc.TCallback<void>);
copyFile(src: misc.PathLike, dest: misc.PathLike, flags: misc.TFlagsCopy, callback: misc.TCallback<void>);
copyFile(src: misc.PathLike, dest: misc.PathLike, a, b?) {
throw new Error('Not implemented');
}
public readonly copyFile: FsCallbackApi['copyFile'] = (src: misc.PathLike, dest: misc.PathLike, a, b?): void => {
const srcFilename = pathToFilename(src);
const destFilename = pathToFilename(dest);
let flags: misc.TFlagsCopy;
let callback: misc.TCallback<void>;
if (typeof a === 'function') {
flags = 0;
callback = a;
} else {
flags = a;
callback = b;
}
validateCallback(callback);
const [oldFolder, oldName] = pathToLocation(srcFilename);
const [newFolder, newName] = pathToLocation(destFilename);
(async () => {
const oldFile = await this.getFile(oldFolder, oldName, 'copyFile');
const newDir = await this.getDir(newFolder, false, 'copyFile');
const newFile = await newDir.getFileHandle(newName, { create: true });
const writable = await newFile.createWritable({ keepExistingData: false });
const oldData = await oldFile.getFile();
await writable.write(await oldData.arrayBuffer());
await writable.close();
})().then(
() => callback(null),
error => callback(error),
);
};

public readonly unlink: FsCallbackApi['unlink'] = (path: misc.PathLike, callback: misc.TCallback<void>): void => {
const filename = pathToFilename(path);
Expand Down
13 changes: 13 additions & 0 deletions src/fsa-to-node/__tests__/FsaNodeFs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -547,3 +547,16 @@ describe('.realpath()', () => {
expect(path).toBe('/folder/file');
});
});

describe('.copyFile()', () => {
test('can copy a file', async () => {
const { fs, mfs } = setup({ folder: { file: 'test' }, 'empty-folder': null, 'f.html': 'test' });
await fs.promises.copyFile('/folder/file', '/folder/file2');
expect(mfs.__vol.toJSON()).toStrictEqual({
'/mountpoint/folder/file': 'test',
'/mountpoint/folder/file2': 'test',
'/mountpoint/empty-folder': null,
'/mountpoint/f.html': 'test',
});
});
});

0 comments on commit de2bb0a

Please sign in to comment.