0
# File Storage
1
2
Local file system cache stores with support for both basic file storage and automatic cleanup of expired cache entries. Provides reliable local caching with hierarchical directory organization.
3
4
## Capabilities
5
6
### FileStore
7
8
Basic file-based cache store that persists cached values to the local file system with JSON and binary data support.
9
10
```javascript { .api }
11
/**
12
* Local file-based cache store with JSON and binary support
13
* Organizes cache files in a hierarchical directory structure for performance
14
* @template T - Type of cached values
15
*/
16
class FileStore<T> {
17
/**
18
* Create a new file store instance
19
* @param options - Configuration options for the file store
20
*/
21
constructor(options: FileOptions);
22
23
/**
24
* Read cached value from file system
25
* @param key - Cache key as Buffer
26
* @returns Promise resolving to cached value or null if not found/corrupted
27
*/
28
get(key: Buffer): Promise<T | null>;
29
30
/**
31
* Write value to file system with automatic directory creation
32
* @param key - Cache key as Buffer
33
* @param value - Value to cache (JSON serializable or Buffer)
34
* @returns Promise that resolves when write is complete
35
*/
36
set(key: Buffer, value: T): Promise<void>;
37
38
/**
39
* Clear all cached files by removing all cache directories
40
* @returns void (synchronous operation)
41
*/
42
clear(): void;
43
}
44
45
/**
46
* Configuration options for FileStore
47
*/
48
interface FileOptions {
49
/**
50
* Root directory path where cache files will be stored
51
*/
52
root: string;
53
}
54
```
55
56
**Usage Examples:**
57
58
```javascript
59
const { FileStore, stableHash } = require("metro-cache");
60
61
// Create file store
62
const fileStore = new FileStore({ root: "./build-cache" });
63
64
// Cache JavaScript compilation result
65
const sourceKey = stableHash({ file: "app.js", transforms: ["babel", "minify"] });
66
const compiledCode = "/* compiled code */";
67
68
await fileStore.set(sourceKey, compiledCode);
69
70
// Retrieve cached result
71
const cached = await fileStore.get(sourceKey);
72
if (cached !== null) {
73
console.log("Cache hit:", cached);
74
}
75
76
// Cache binary data (like source maps)
77
const mapKey = stableHash({ file: "app.js.map" });
78
const sourceMapBuffer = Buffer.from("source map content");
79
80
await fileStore.set(mapKey, sourceMapBuffer);
81
```
82
83
### AutoCleanFileStore
84
85
File store with automatic cleanup of old cached files based on configurable age thresholds and cleanup intervals.
86
87
```javascript { .api }
88
/**
89
* File store that automatically cleans up old cached files
90
* Extends FileStore with periodic cleanup functionality
91
* @template T - Type of cached values
92
*/
93
class AutoCleanFileStore<T> extends FileStore<T> {
94
/**
95
* Create a new auto-cleaning file store instance
96
* @param options - Configuration options including cleanup settings
97
*/
98
constructor(options: CleanOptions);
99
}
100
101
/**
102
* Configuration options for AutoCleanFileStore
103
*/
104
interface CleanOptions extends FileOptions {
105
/**
106
* Cleanup interval in milliseconds (default: 10 minutes)
107
*/
108
intervalMs?: number;
109
110
/**
111
* Age threshold for file cleanup in milliseconds (default: 3 days)
112
*/
113
cleanupThresholdMs?: number;
114
}
115
```
116
117
**Usage Examples:**
118
119
```javascript
120
const { AutoCleanFileStore } = require("metro-cache");
121
122
// Create auto-cleaning file store
123
const autoCleanStore = new AutoCleanFileStore({
124
root: "./temp-cache",
125
intervalMs: 5 * 60 * 1000, // Clean every 5 minutes
126
cleanupThresholdMs: 24 * 60 * 60 * 1000 // Delete files older than 1 day
127
});
128
129
// Use normally - cleanup happens automatically in background
130
await autoCleanStore.set(key, value);
131
const result = await autoCleanStore.get(key);
132
```
133
134
## File Organization
135
136
Both FileStore implementations use a hierarchical directory structure for optimal file system performance:
137
138
- **Root Directory**: Specified in options.root
139
- **First Level**: First byte of cache key as hex (00-FF, creating 256 subdirectories)
140
- **File Name**: Remaining bytes of cache key as hex
141
142
Example file path for key `Buffer.from([0x12, 0x34, 0x56, 0x78])`:
143
```
144
{root}/12/3456789...
145
```
146
147
## Data Serialization
148
149
File stores handle different data types automatically:
150
151
- **JavaScript Objects**: Serialized as JSON
152
- **Buffer Data**: Stored as binary with null byte (0x00) prefix for identification
153
- **Primitive Values**: Serialized as JSON
154
155
## Error Handling
156
157
File stores provide robust error handling:
158
159
- **Read Errors**: ENOENT (file not found) and SyntaxError (corrupted JSON) return null
160
- **Write Errors**: ENOENT triggers automatic parent directory creation and retry
161
- **Cleanup Errors**: AutoCleanFileStore logs warnings but continues operation
162
163
## Cleanup Behavior
164
165
AutoCleanFileStore cleanup process:
166
167
1. **Scheduled Execution**: Runs at specified intervalMs
168
2. **File Scanning**: Recursively scans all files in the cache directory
169
3. **Age Check**: Compares file modification time against cleanupThresholdMs
170
4. **Safe Deletion**: Only deletes files, never directories
171
5. **Error Resilience**: Continues cleanup even if individual file deletions fail