0
# Storage Inspection
1
2
Methods for inspecting and iterating over stored data, including key enumeration and batch processing capabilities. These methods allow you to examine the contents of your storage without needing to know specific keys in advance.
3
4
## Capabilities
5
6
### Get Storage Length
7
8
Returns the number of items currently stored in the storage instance.
9
10
```javascript { .api }
11
/**
12
* Gets the number of items in storage
13
* @param callback - Optional callback function
14
* @returns Promise resolving to the number of keys
15
*/
16
function length(callback?: (err: any, numberOfKeys: number) => void): Promise<number>;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
import localforage from 'localforage';
23
24
// Check how many items are stored
25
const count = await localforage.length();
26
console.log(`Storage contains ${count} items`);
27
28
// Using callbacks
29
localforage.length((err, numberOfKeys) => {
30
if (err) {
31
console.error('Error getting length:', err);
32
} else {
33
console.log('Number of keys:', numberOfKeys);
34
}
35
});
36
37
// Conditional logic based on storage size
38
const itemCount = await localforage.length();
39
if (itemCount === 0) {
40
console.log('Storage is empty');
41
} else if (itemCount > 100) {
42
console.log('Storage is getting full, consider cleanup');
43
}
44
```
45
46
### Get Key by Index
47
48
Retrieves the key name at the specified index. Keys are ordered differently depending on the storage driver being used.
49
50
```javascript { .api }
51
/**
52
* Gets the key at the specified index
53
* @param keyIndex - The index of the key to retrieve (0-based)
54
* @param callback - Optional callback function
55
* @returns Promise resolving to the key name
56
*/
57
function key(keyIndex: number, callback?: (err: any, key: string) => void): Promise<string>;
58
```
59
60
**Usage Examples:**
61
62
```javascript
63
import localforage from 'localforage';
64
65
// Get the first key
66
const firstKey = await localforage.key(0);
67
console.log('First key:', firstKey);
68
69
// Get the last key
70
const length = await localforage.length();
71
if (length > 0) {
72
const lastKey = await localforage.key(length - 1);
73
console.log('Last key:', lastKey);
74
}
75
76
// Using callbacks
77
localforage.key(2, (err, keyName) => {
78
if (err) {
79
console.error('Error getting key:', err);
80
} else {
81
console.log('Key at index 2:', keyName);
82
}
83
});
84
85
// Iterate through all keys using indices
86
const totalKeys = await localforage.length();
87
for (let i = 0; i < totalKeys; i++) {
88
const keyName = await localforage.key(i);
89
console.log(`Key ${i}: ${keyName}`);
90
}
91
```
92
93
### Get All Keys
94
95
Retrieves an array of all key names in storage.
96
97
```javascript { .api }
98
/**
99
* Gets all keys currently in storage
100
* @param callback - Optional callback function
101
* @returns Promise resolving to an array of key names
102
*/
103
function keys(callback?: (err: any, keys: string[]) => void): Promise<string[]>;
104
```
105
106
**Usage Examples:**
107
108
```javascript
109
import localforage from 'localforage';
110
111
// Get all keys
112
const allKeys = await localforage.keys();
113
console.log('All keys:', allKeys);
114
// Output: ['user', 'settings', 'cache', 'session']
115
116
// Check if a specific key exists
117
const keyList = await localforage.keys();
118
const hasUserData = keyList.includes('userData');
119
120
// Filter keys by pattern
121
const allKeys = await localforage.keys();
122
const cacheKeys = allKeys.filter(key => key.startsWith('cache_'));
123
const tempKeys = allKeys.filter(key => key.includes('temp'));
124
125
// Using callbacks
126
localforage.keys((err, keyList) => {
127
if (err) {
128
console.error('Error getting keys:', err);
129
} else {
130
console.log('Available keys:', keyList);
131
}
132
});
133
134
// Process all stored data
135
const keys = await localforage.keys();
136
for (const key of keys) {
137
const value = await localforage.getItem(key);
138
console.log(`${key}:`, value);
139
}
140
```
141
142
### Iterate Over Storage
143
144
Iterates over all items in storage, calling the provided function for each key/value pair. This is more efficient than manually iterating with `keys()` and `getItem()`.
145
146
```javascript { .api }
147
/**
148
* Iterates over all items in storage
149
* @param iteratee - Function called for each item (value, key, iterationNumber) => result
150
* @param callback - Optional callback function
151
* @returns Promise resolving to the result of the iteration
152
*/
153
function iterate<T, U>(
154
iteratee: (value: T, key: string, iterationNumber: number) => U,
155
callback?: (err: any, result: U) => void
156
): Promise<U>;
157
```
158
159
**Usage Examples:**
160
161
```javascript
162
import localforage from 'localforage';
163
164
// Simple iteration - log all items
165
await localforage.iterate((value, key, iterationNumber) => {
166
console.log(`[${iterationNumber}] ${key}:`, value);
167
});
168
169
// Count items matching a condition
170
let userCount = 0;
171
await localforage.iterate((value, key) => {
172
if (key.startsWith('user_')) {
173
userCount++;
174
}
175
});
176
console.log(`Found ${userCount} user records`);
177
178
// Find and return specific item
179
const foundUser = await localforage.iterate((value, key) => {
180
if (key === 'currentUser') {
181
return value; // This stops iteration and returns the value
182
}
183
// Continue iteration
184
});
185
186
// Calculate total size (conceptual example)
187
let totalItems = 0;
188
await localforage.iterate((value, key, iterationNumber) => {
189
totalItems++;
190
console.log(`Processing item ${iterationNumber + 1}: ${key}`);
191
});
192
193
// Using callbacks
194
localforage.iterate((value, key, iterationNumber) => {
195
// Process each item
196
console.log(`Item ${iterationNumber}: ${key} = ${value}`);
197
198
// Return undefined to continue iteration
199
// Return any other value to stop and return that value
200
}, (err, result) => {
201
if (err) {
202
console.error('Iteration error:', err);
203
} else {
204
console.log('Iteration completed, result:', result);
205
}
206
});
207
208
// Early termination example
209
const searchResult = await localforage.iterate((value, key) => {
210
if (typeof value === 'object' && value.type === 'important') {
211
return value; // Found what we're looking for, stop iterating
212
}
213
// Continue iterating
214
});
215
216
// Collect all values into an array
217
const allValues = [];
218
await localforage.iterate((value, key) => {
219
allValues.push({ key, value });
220
});
221
console.log('All stored data:', allValues);
222
```
223
224
## Advanced Usage Patterns
225
226
### Storage Statistics
227
228
```javascript
229
// Get comprehensive storage statistics
230
async function getStorageStats() {
231
const keys = await localforage.keys();
232
const length = await localforage.length();
233
const keysByPrefix = {};
234
235
keys.forEach(key => {
236
const prefix = key.split('_')[0];
237
keysByPrefix[prefix] = (keysByPrefix[prefix] || 0) + 1;
238
});
239
240
return {
241
totalItems: length,
242
keyPrefixes: keysByPrefix,
243
allKeys: keys
244
};
245
}
246
247
const stats = await getStorageStats();
248
console.log('Storage statistics:', stats);
249
```
250
251
### Batch Operations
252
253
```javascript
254
// Delete all keys matching a pattern
255
async function clearKeysByPattern(pattern) {
256
const keys = await localforage.keys();
257
const keysToRemove = keys.filter(key => key.includes(pattern));
258
259
for (const key of keysToRemove) {
260
await localforage.removeItem(key);
261
}
262
263
return keysToRemove.length;
264
}
265
266
const removedCount = await clearKeysByPattern('temp_');
267
console.log(`Removed ${removedCount} temporary items`);
268
```
269
270
### Storage Migration
271
272
```javascript
273
// Migrate data with key transformation
274
async function migrateKeys(oldPrefix, newPrefix) {
275
const keys = await localforage.keys();
276
const keysToMigrate = keys.filter(key => key.startsWith(oldPrefix));
277
278
for (const oldKey of keysToMigrate) {
279
const value = await localforage.getItem(oldKey);
280
const newKey = oldKey.replace(oldPrefix, newPrefix);
281
282
await localforage.setItem(newKey, value);
283
await localforage.removeItem(oldKey);
284
}
285
286
return keysToMigrate.length;
287
}
288
289
const migratedCount = await migrateKeys('old_', 'new_');
290
console.log(`Migrated ${migratedCount} keys`);
291
```
292
293
## Performance Considerations
294
295
- **`iterate()`** is more efficient than manually using `keys()` + `getItem()` in a loop
296
- **Key order** is not guaranteed and may vary between storage drivers
297
- **Large datasets** may benefit from batch processing using `iterate()` with early termination
298
- **Memory usage** with `keys()` grows with the number of stored items
299
300
```javascript
301
// Efficient: Use iterate() for processing all items
302
await localforage.iterate((value, key) => {
303
processItem(key, value);
304
});
305
306
// Less efficient: Manual iteration
307
const keys = await localforage.keys();
308
for (const key of keys) {
309
const value = await localforage.getItem(key);
310
processItem(key, value);
311
}
312
```