File System Utilities
The file system utilities provide common file and directory operations with Promise-based APIs for Node.js applications.
Installation
Import the utilities from the kempo-server package:
import { ensureDir, copyDir, emptyDir } from 'kempo-server/utils/fs-utils';
ensureDir(dirPath)
Ensures that a directory exists, creating it and any necessary parent directories if they don't exist. Similar to mkdir -p.
Parameters
dirPath(string) - The directory path to ensure exists
Returns
Promise that resolves when the directory is confirmed to exist.
Example
import { ensureDir } from 'kempo-server/utils/fs-utils';
await ensureDir('./dist/assets');
await ensureDir('./logs/app');
// Creates ./dist/assets and ./logs/app directories if they don't exist
copyDir(srcPath, destPath)
Recursively copies an entire directory structure from source to destination.
Parameters
srcPath(string) - The source directory to copy fromdestPath(string) - The destination directory to copy to
Returns
Promise that resolves when the copy operation is complete.
Example
import { copyDir } from 'kempo-server/utils/fs-utils';
await copyDir('./src/assets', './dist/assets');
await copyDir('./public', './dist');
// Copies all files and subdirectories from src to dest
emptyDir(dirPath)
Removes all contents of a directory without deleting the directory itself.
Parameters
dirPath(string) - The directory path to empty
Returns
Promise that resolves when the directory has been emptied.
Example
import { emptyDir } from 'kempo-server/utils/fs-utils';
await emptyDir('./dist');
await emptyDir('./temp');
// Removes all files and subdirectories inside ./dist and ./temp
Common Use Cases
Build Script
import { ensureDir, copyDir, emptyDir } from 'kempo-server/utils/fs-utils';
async function buildProject() {
// Clean previous build
await emptyDir('./dist');
// Ensure build directories exist
await ensureDir('./dist/assets');
await ensureDir('./dist/components');
// Copy static assets
await copyDir('./src/assets', './dist/assets');
await copyDir('./src/public', './dist');
}
Backup Script
import { ensureDir, copyDir } from 'kempo-server/utils/fs-utils';
async function backupProject() {
const timestamp = new Date().toISOString().slice(0, 10);
const backupPath = `./backups/${timestamp}`;
await ensureDir(backupPath);
await copyDir('./src', `${backupPath}/src`);
await copyDir('./config', `${backupPath}/config`);
}
Notes
- All functions use Node.js's Promise-based fs APIs
- Operations are asynchronous and should be awaited
- Functions handle errors appropriately (e.g., ensureDir ignores EEXIST)
- copyDir preserves directory structure recursively