UNPKG

tiny-essentials

Version:

Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.

235 lines (129 loc) โ€ข 5.83 kB
# ๐Ÿ“ Node.js File & Directory Utilities A powerful and flexible utility toolkit for managing files and directories in Node.js using `fs` and `path`. Includes support for JSON operations, text handling, backups, renaming strategies, and more! --- ## ๐Ÿ“ฆ JSON Operations ### `readJsonFile(filePath: string): any` ๐Ÿ“– Reads and parses a JSON file. * Throws an error if the file doesn't exist or contains invalid JSON. * Async version: `readJsonFileAsync`. ### `writeJsonFile(filePath: string, data: any, spaces: number = 2): void` ๐Ÿ’พ Saves a JavaScript object as a formatted JSON file. * Automatically creates the directory if it doesn't exist. * Async version: `writeJsonFileAsync`. --- ## ๐Ÿ“‚ Directory Management ### `ensureDirectory(dirPath: string): void` ๐Ÿ› ๏ธ Ensures a directory exists. Creates it recursively if needed. ### `clearDirectory(dirPath: string): void` ๐Ÿงน Deletes all contents inside a directory while keeping the directory itself. * Async version: `clearDirectoryAsync`. --- ## ๐Ÿงช File Checks ### `fileExists(filePath: string): boolean` ๐Ÿ”Ž Checks if a file exists. ### `dirExists(dirPath: string): boolean` ๐Ÿข Checks if a directory exists. ### `isDirEmpty(dirPath: string): boolean` ๐Ÿ“ญ Checks if a directory is empty. * Async version: `isDirEmptyAsync`. --- ## ๐Ÿ“„ File Operations ### `ensureCopyFile(src: string, dest: string): void` ๐Ÿ“‹ Copies a file from `src` to `dest`, ensuring the destination directory exists. * Async version: `ensureCopyFileAsync`. ### `tryDeleteFile(filePath: string): boolean` ๐Ÿ—‘๏ธ Tries to delete a file if it exists. Returns `true` if deleted. * Async version: `tryDeleteFileAsync`. --- ## ๐Ÿ“ Text Operations ### `writeTextFile(filePath: string, content: string, ops?: fs.WriteFileOptions): void` โœ๏ธ Writes text content to a file. Ensures the directory exists before writing. * Async version: `writeTextFileAsync`. --- ## ๐Ÿงพ Directory Listings ### `listFiles(dirPath: string, recursive?: boolean): string[]` ๐Ÿ“ƒ Lists all files and dirs in a directory. Can be recursive. * Async version: `listFilesAsync`. ### `listDirs(dirPath: string, recursive?: boolean): string[]` ๐Ÿ“ Lists all directories in a directory. Can be recursive. * Async version: `listDirsAsync`. --- ## ๐Ÿ“ File Info ### `fileSize(filePath: string): number` โš–๏ธ Gets the size of a single file in bytes. * Async version: `fileSizeAsync`. ### `dirSize(dirPath: string): number` ๐Ÿ“ฆ Gets the total size of all files inside a directory (recursive). * Async version: `dirSizeAsync`. --- ## ๐Ÿ’พ Backup Utilities ### `backupFile(filePath: string, ext: string = 'bak'): void` ๐Ÿ›Ÿ Creates a timestamped `.bak` copy of the file. * Async version: `backupFileAsync`. ### `getLatestBackupPath(filePath: string, ext: string = 'bak'): void` ๐Ÿ“ฆ Returns the **most recent backup file path** for a given file, without modifying anything. Useful for checking which backup would be restored. ### `restoreLatestBackup(filePath: string, ext: string = 'bak'): void` โ™ป๏ธ Restores the most recent backup for the file. Output: `/home/yasmin/notes.txt.bak.20250625T153000` ``` <file name>.<ext>.<timestamp> ``` * Async version: `restoreLatestBackupAsync`. --- ## ๐Ÿ”„ Rename Utilities ### `renameFileBatch(dirPath, renameFn, extensions?)` ๐Ÿง  Renames all files using a custom renaming function. * Only affects files with the specified extensions (if any). ### `renameFileRegex(dirPath, pattern, replacement, extensions?)` ๐Ÿ”ก Renames files using a regex pattern and replacement string. ### `renameFileAddPrefixSuffix(dirPath, { prefix, suffix }, extensions?)` ๐Ÿ”  Adds a prefix and/or suffix to each filename. ### `renameFileNormalizeCase(dirPath, mode, extensions?, normalizeExt: boolean = false)` ๐Ÿ†Ž Converts filenames to lowercase or uppercase. * `mode`: `'lower'` or `'upper'`. ### `renameFilePadNumbers(dirPath, totalDigits, extensions?)` ๐Ÿ”ข Pads the first numeric sequence in a filename with leading zeros. --- ## ๐Ÿ”ก `renameFileNormalizeCase(dirPath, mode = 'lower', extensions = [])` Normalizes all filenames in a directory to lowercase or uppercase. ### ๐Ÿ“ฅ Parameters: * `dirPath` *(string)*: Path to the target directory. * `mode` *(`'lower' | 'upper'`)*: Case conversion mode. * `'lower'`: Converts filenames to lowercase. * `'upper'`: Converts filenames to uppercase. * `extensions` *(string\[])* *(optional)*: List of file extensions to filter. If provided, only files with these extensions will be renamed. ### ๐ŸŽฏ Example: ```js renameFileNormalizeCase('./images', 'lower', ['.jpg', '.png']); ``` ๐Ÿ” **Effect**: `Photo01.JPG` โ†’ `photo01.jpg` `Logo.PNG` โ†’ `logo.png` --- ## ๐Ÿ”ข `renameFilePadNumbers(dirPath, totalDigits = 3, extensions = [])` Pads the first numeric sequence found in each filename to a specified number of digits. ### ๐Ÿ“ฅ Parameters: * `dirPath` *(string)*: Path to the target directory. * `totalDigits` *(number)*: Minimum number of digits. Numbers will be padded with leading zeros. * `extensions` *(string\[])* *(optional)*: Only rename files with matching extensions. ### ๐ŸŽฏ Example: ```js renameFilePadNumbers('./screenshots', 4, ['.jpg']); ``` ๐Ÿ” **Effect**: `screenshot1.jpg` โ†’ `screenshot0001.jpg` `photo23.jpg` โ†’ `photo0023.jpg` ### ๐Ÿง  Notes: * Only the **first** number in the filename is affected. * If a filename has no digits, it will not be changed. --- ## ๐Ÿ“ฆ More Example Use ```js import { readJsonFile, writeJsonFile, listFiles, backupFile } from './utils/files.js'; const data = readJsonFile('./config/settings.json'); data.debug = false; writeJsonFile('./config/settings.json', data); const files = listFiles('./src/assets', true); console.log('Found files:', files); backupFile('./config/settings.json'); ```