Skip to content

Commit 9ed9344

Browse files
committed
feat(fs): copy file functions
1 parent 92eee50 commit 9ed9344

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

packages/fs/src/file.lib.ts

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,74 @@ export class FsFile<
423423
this.removeSync();
424424
}
425425

426+
/**
427+
* Copy the file to a new location.
428+
*
429+
* @param toFile - The destination path for the file or an existing FsFile instance
430+
* @returns A promise that resolves to the new copied file
431+
* @throws If the copy operation fails or if parent directory creation fails
432+
*
433+
* ```typescript
434+
* import { fsFile } from "@synstack/fs";
435+
*
436+
* const sourceFile = fsFile("./source.txt");
437+
* const copiedFile = await sourceFile.copy("./backup/source.txt");
438+
* // Both files now exist with the same content
439+
* ```
440+
*/
441+
public async copyTo(toFile: FsFile | string): Promise<FsFile> {
442+
const destFile = FsFile.from(toFile);
443+
const destDir = destFile.dir().path;
444+
try {
445+
// Ensure destination directory exists
446+
await fs.mkdir(destDir, { recursive: true });
447+
// Copy the file
448+
await fs.copyFile(this._path, destFile.path);
449+
return destFile;
450+
} catch (error) {
451+
throw new Error(
452+
`Failed to copy file from ${this._path} to ${destFile.path}`,
453+
{
454+
cause: error,
455+
},
456+
);
457+
}
458+
}
459+
460+
/**
461+
* Copy the file to a new location synchronously.
462+
*
463+
* @param toFile - The destination path for the file or an existing FsFile instance
464+
* @returns The new copied file
465+
* @throws If the copy operation fails or if parent directory creation fails
466+
*
467+
* ```typescript
468+
* import { fsFile } from "@synstack/fs";
469+
*
470+
* const sourceFile = fsFile("./source.txt");
471+
* const copiedFile = sourceFile.copySync("./backup/source.txt");
472+
* // Both files now exist with the same content
473+
* ```
474+
*/
475+
public copyToSync(toFile: FsFile | string): FsFile {
476+
const destFile = FsFile.from(toFile);
477+
const destDir = destFile.dir().path;
478+
try {
479+
// Ensure destination directory exists
480+
fsSync.mkdirSync(destDir, { recursive: true });
481+
// Copy the file
482+
fsSync.copyFileSync(this._path, destFile.path);
483+
return destFile;
484+
} catch (error) {
485+
throw new Error(
486+
`Failed to copy file from ${this._path} to ${destFile.path}`,
487+
{
488+
cause: error,
489+
},
490+
);
491+
}
492+
}
493+
426494
/**
427495
* Move the file to a new location.
428496
*

0 commit comments

Comments
 (0)