Operations for managing cache state, file paths, and cache maintenance including clearing all items and ensuring proper directory structure.
Removes all cached items within the cache's namespace.
/**
* Removes all cached items from the file system within this cache's namespace
* @returns Promise that resolves when all files are removed
*/
clear(): Promise<void>;Usage Examples:
// Clear all items in default namespace
await cache.clear();
// Clear namespace-specific cache
const userCache = Cache({ ns: "users" });
await userCache.clear(); // Only removes files with "users" namespace
// Clear before re-initialization
await cache.clear();
console.log("Cache cleared, starting fresh");
// Conditional clearing based on criteria
const cacheAge = Date.now() - lastCacheReset;
if (cacheAge > 24 * 60 * 60 * 1000) { // 24 hours
await cache.clear();
lastCacheReset = Date.now();
}Checks if a cached file exists for a given key without retrieving the content.
/**
* Determines whether the cached file exists for the given key
* @param key - The cache key to check
* @returns Promise resolving to true if file exists, false otherwise
*/
fileExists(key: string): Promise<boolean>;Usage Examples:
// Check if item exists before retrieval
if (await cache.fileExists("user:123")) {
const user = await cache.get("user:123");
console.log("User found:", user);
} else {
console.log("User not in cache");
}
// Conditional operations
const configExists = await cache.fileExists("app:config");
if (!configExists) {
await cache.set("app:config", defaultConfig);
}
// Batch existence checking
const keys = ["session:1", "session:2", "session:3"];
const existenceMap = await Promise.all(
keys.map(async key => ({
key,
exists: await cache.fileExists(key)
}))
);Generates the file system path for a given cache key.
/**
* Generates the file path for the given cache key
* @param key - The cache key
* @returns Absolute file path where the cached item would be stored
* @throws Error if key is empty or invalid
*/
path(key: string): string;Usage Examples:
// Get file path for debugging
const filePath = cache.path("user:123");
console.log(`Cache file location: ${filePath}`);
// Use path in external tools
const cachePath = cache.path("data:backup");
await copyFile(sourceFile, cachePath);
// Validate path structure
const paths = ["user:1", "user:2", "user:3"].map(key => cache.path(key));
console.log("Cache files will be stored at:", paths);
// Error handling for invalid keys
try {
const invalidPath = cache.path(""); // Throws error
} catch (error) {
console.error("Path generation failed:", error.message);
}Ensures the base cache directory exists before operations.
/**
* Ensures that the base cache directory exists, creating it if necessary
* @returns Promise that resolves when directory is confirmed to exist
*/
ensureBasePath(): Promise<void>;Usage Examples:
// Manually ensure directory exists
await cache.ensureBasePath();
console.log("Cache directory ready");
// Pre-create directory for external tools
await cache.ensureBasePath();
const baseDir = cache.basePath;
await runExternalScript(baseDir);
// Ensure directory before bulk operations
await cache.ensureBasePath();
await cache.save(largeDataSet);Access to read-only configuration and state properties.
/**
* Read-only properties providing access to cache configuration
*/
readonly basePath: string; // Absolute path to cache directory
readonly ns?: any; // Cache namespace identifier
readonly extension?: string; // File extension for cache files
readonly hash: HashAlgorithm; // Hash algorithm for key generation
readonly ttl: number; // Default TTL in secondsUsage Examples:
// Access configuration for logging
console.log(`Cache directory: ${cache.basePath}`);
console.log(`Default TTL: ${cache.ttl} seconds`);
console.log(`Hash algorithm: ${cache.hash}`);
// Use in conditional logic
if (cache.extension) {
console.log(`Files will have .${cache.extension} extension`);
}
// Debug namespace configuration
if (cache.ns) {
console.log(`Cache namespace: ${JSON.stringify(cache.ns)}`);
}/**
* Mutable state property tracking directory existence
*/
basePathExists?: boolean; // Whether base directory has been verified/createdUsage Examples:
// Check if directory has been initialized
if (!cache.basePathExists) {
console.log("First cache operation will create directory");
}
// Monitor initialization state
console.log(`Directory initialized: ${cache.basePathExists || false}`);// Schedule periodic cache clearing
setInterval(async () => {
await cache.clear();
console.log("Cache cleared on schedule");
}, 24 * 60 * 60 * 1000); // Daily
// Size-based maintenance
const cacheStats = await getCacheStats(cache.basePath);
if (cacheStats.size > MAX_CACHE_SIZE) {
await cache.clear();
}// Ensure cache is ready before app starts
async function initializeCache() {
await cache.ensureBasePath();
// Pre-populate critical data
if (!await cache.fileExists("app:config")) {
await cache.set("app:config", await loadDefaultConfig());
}
console.log("Cache initialized and ready");
}
await initializeCache();// Smart caching with existence checks
async function getCachedOrFetch(key: string, fetchFn: () => Promise<any>) {
if (await cache.fileExists(key)) {
return await cache.get(key);
}
const data = await fetchFn();
await cache.set(key, data);
return data;
}
// Usage
const userData = await getCachedOrFetch(
"user:123",
() => fetchUserFromAPI("123")
);// Robust cache operations with fallback
async function safeGet(key: string, fallback: any = null) {
try {
if (await cache.fileExists(key)) {
return await cache.get(key);
}
} catch (error) {
console.warn(`Cache read failed for ${key}:`, error.message);
}
return fallback;
}
// Robust cache clearing with error handling
async function safeClear() {
try {
await cache.clear();
console.log("Cache cleared successfully");
} catch (error) {
console.error("Cache clear failed:", error.message);
// Fallback: try to clear individual files
// Implementation depends on requirements
}
}