@clipwhisperer/common
Version:
ClipWhisperer Common - Shared library providing core utilities, database schemas, authentication, bucket management, and common functionality across all ClipWhisperer microservices
79 lines (71 loc) • 1.81 kB
text/typescript
/**
* File System Utilities
* Centralized file system operations used across services
*/
import fs from "fs";
import path from "path";
/**
* Ensure a directory exists, create it if it doesn't
*/
export function ensureDirectoryExists(directory: string): boolean {
const exists = fs.existsSync(directory);
if (!exists) {
fs.mkdirSync(directory, { recursive: true });
}
return exists;
}
/**
* Check if a directory exists and create it if it doesn't
* @param directory - The path to the directory to check
* @returns {boolean} True if the directory existed, false if it was created
*/
export function checkDirectoryExists(directory: string): boolean {
const exists = fs.existsSync(directory);
if (!exists) {
fs.mkdirSync(directory, { recursive: true });
}
return exists;
}
/**
* Get file size in bytes
*/
export function getFileSize(filePath: string): number {
try {
const stats = fs.statSync(filePath);
return stats.size;
} catch (error) {
return 0;
}
}
/**
* Check if file exists
*/
export function fileExists(filePath: string): boolean {
return fs.existsSync(filePath);
}
/**
* Delete file if it exists
*/
export function deleteFileIfExists(filePath: string): boolean {
try {
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
return true;
}
return false;
} catch (error) {
return false;
}
}
/**
* Create file path within project directory
*/
export function createProjectPath(...segments: string[]): string {
return path.join(process.cwd(), ...segments);
}
/**
* Sanitize filename for safe file system usage
*/
export function sanitizeFilename(filename: string): string {
return filename.replace(/[^a-z0-9.-]/gi, '_');
}