* Reads a file with caching. Returns both content and encoding. * Cache key includes file path and modification time for automatic invalidation.
(filePath: string)
| 22 | * Cache key includes file path and modification time for automatic invalidation. |
| 23 | */ |
| 24 | readFile(filePath: string): { content: string; encoding: BufferEncoding } { |
| 25 | const fs = getFsImplementation() |
| 26 | |
| 27 | // Get file stats for cache invalidation |
| 28 | let stats |
| 29 | try { |
| 30 | stats = fs.statSync(filePath) |
| 31 | } catch (error) { |
| 32 | // File was deleted, remove from cache and re-throw |
| 33 | this.cache.delete(filePath) |
| 34 | throw error |
| 35 | } |
| 36 | |
| 37 | const cacheKey = filePath |
| 38 | const cachedData = this.cache.get(cacheKey) |
| 39 | |
| 40 | // Check if we have valid cached data |
| 41 | if (cachedData && cachedData.mtime === stats.mtimeMs) { |
| 42 | return { |
| 43 | content: cachedData.content, |
| 44 | encoding: cachedData.encoding, |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // Cache miss or stale data - read the file |
| 49 | const encoding = detectFileEncoding(filePath) |
| 50 | const content = fs |
| 51 | .readFileSync(filePath, { encoding }) |
| 52 | .replaceAll('\r\n', '\n') |
| 53 | |
| 54 | // Update cache |
| 55 | this.cache.set(cacheKey, { |
| 56 | content, |
| 57 | encoding, |
| 58 | mtime: stats.mtimeMs, |
| 59 | }) |
| 60 | |
| 61 | // Evict oldest entries if cache is too large |
| 62 | if (this.cache.size > this.maxCacheSize) { |
| 63 | const firstKey = this.cache.keys().next().value |
| 64 | if (firstKey) { |
| 65 | this.cache.delete(firstKey) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | return { content, encoding } |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * Clears the entire cache. Useful for testing or memory management. |
no test coverage detected