UNPKG

@file-cache/core

Version:

A cache for file metadata or file content.

110 lines (107 loc) 2.96 kB
import path from 'node:path'; import { createFileCache } from './createFileCache.mjs'; import fs from 'node:fs/promises'; import { createCacheKey } from './createCacheKey.mjs'; import { createNoCache } from './noCache.mjs'; /** * Delete cache file * Note: It does not clear in-memory cache in the cache. * @param options */ const deleteCacheFile = async options => { const findCacheDir = await import('find-cache-dir').then(m => m.default); const cacheDir = options.cacheDirectory ? options.cacheDirectory : // node_modules/.cache/<name> // https://github.com/sindresorhus/find-cache-dir findCacheDir({ name: options.name, create: true }); if (!cacheDir) { throw new Error(`Not found cache directory. Please set cacheDirectory option or findCacheDir is failed.`); } const cacheFile = path.join(cacheDir, createCacheKey(options.keys)); try { await fs.unlink(cacheFile); return true; } catch { return false; } }; const getPackageName = async pkgPath => { const pkgFile = path.join(pkgPath, "package.json"); try { const pkg = await fs.readFile(pkgFile, "utf8"); const pkgJson = JSON.parse(pkg); return pkgJson.name; } catch { return "file-cache"; } }; /** * Create cache instance * @param options */ const createCache = async options => { if (options.noCache) { return createNoCache(); // disable cache. It is noop implemention. } const findCacheDir = await import('find-cache-dir').then(m => m.default); const cacheDir = options.cacheDirectory ? options.cacheDirectory : // node_modules/.cache/<name> // https://github.com/sindresorhus/find-cache-dir findCacheDir({ name: options.name }); if (!cacheDir) { throw new Error(`Not found cache directory. Please set cacheDirectory option or findCacheDir is failed.`); } await fs.mkdir(cacheDir, { recursive: true }); const cacheFile = path.join(cacheDir, createCacheKey(options.keys)); const cache = await createFileCache(cacheFile, options.mode); return { /** * Experimental method * @param cb */ async try(cb) { await cb(); await this.reconcile(); }, /** * Get cache status and update the cache value * You need to confirm the status via call `reconcile()` after that * @param filePath */ async getAndUpdateCache(filePath) { const descriptor = await cache.getFileDescriptor(filePath); return { error: descriptor.error, changed: descriptor.changed }; }, /** * Delete cache value for the key * @param filePath */ async delete(filePath) { return cache.delete(filePath); }, /** * Clear cache values */ async clear() { cache.clear(); }, /** * Confirm the changes */ async reconcile() { return cache.reconcile(); } }; }; export { createCache, deleteCacheFile }; //# sourceMappingURL=index.mjs.map