feat(SmartFile): Add rename functionality to SmartFile class
This commit is contained in:
parent
a2bd049ebd
commit
16ded5c3cf
@ -1,5 +1,11 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-01-07 - 11.1.0 - feat(SmartFile)
|
||||
Add rename functionality to SmartFile class
|
||||
|
||||
- Implemented a new method to rename a file within the SmartFile class.
|
||||
- The rename method updates the file path and optionally writes the renamed file to the disk.
|
||||
|
||||
## 2024-12-15 - 11.0.23 - fix(fs)
|
||||
Handle errors in toObjectSync method
|
||||
|
||||
|
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartfile',
|
||||
version: '11.0.23',
|
||||
version: '11.1.0',
|
||||
description: 'Provides comprehensive tools for efficient file management in Node.js using TypeScript, including handling streams, virtual directories, and various file operations.'
|
||||
}
|
||||
|
@ -212,6 +212,43 @@ export class SmartFile extends plugins.smartjson.Smartjson {
|
||||
await fs.remove(plugins.path.join(this.base, this.path));
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames the file to the specified new name.
|
||||
* - Updates the `path` property with the new name.
|
||||
* - Writes the file to the new location if it exists on disk.
|
||||
* @param newName The new name of the file (including extension if applicable).
|
||||
* @param writeToDisk (optional) If true, also renames the file on the disk.
|
||||
* @returns The updated file path after renaming.
|
||||
*/
|
||||
public async rename(newName: string, writeToDisk: boolean = false): Promise<string> {
|
||||
// Validate the new name
|
||||
if (!newName || typeof newName !== 'string') {
|
||||
throw new Error('Invalid new name provided.');
|
||||
}
|
||||
|
||||
// Extract the directory path
|
||||
const oldFilePath = this.path;
|
||||
const dirPath = plugins.path.dirname(this.path);
|
||||
|
||||
// Create the new file path
|
||||
const newFilePath = plugins.path.join(dirPath, newName);
|
||||
|
||||
// Update the `path` property
|
||||
this.path = newFilePath;
|
||||
|
||||
// Optionally write the renamed file to disk
|
||||
if (writeToDisk) {
|
||||
const oldAbsolutePath = plugins.smartpath.transform.makeAbsolute(oldFilePath, this.base);
|
||||
const newAbsolutePath = plugins.smartpath.transform.makeAbsolute(newFilePath, this.base);
|
||||
|
||||
// Rename the file on disk
|
||||
await plugins.fsExtra.rename(oldAbsolutePath, newAbsolutePath);
|
||||
}
|
||||
|
||||
// Return the new path
|
||||
return this.path;
|
||||
}
|
||||
|
||||
// -----------------------------------------------
|
||||
// vinyl compatibility
|
||||
// -----------------------------------------------
|
||||
|
Loading…
x
Reference in New Issue
Block a user