Super-easy (and fast) persistent data structures in Node.js, modeled after HTML5 localStorage
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Core persistence operations for storing, retrieving, updating, and removing data with optional TTL (time-to-live) support.
Stores a key-value pair with optional TTL configuration.
/**
* Stores a key-value pair with optional TTL configuration
* @param key - The key to store the value under
* @param value - The value to store (will be serialized)
* @param options - Optional configuration including TTL
* @returns Promise resolving to storage result
*/
async function setItem(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;
// Alias
async function set(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;Usage Examples:
const storage = require('node-persist');
await storage.init();
// Basic storage
await storage.setItem('username', 'alice');
await storage.setItem('user', { name: 'Alice', age: 30, active: true });
// With TTL in milliseconds
await storage.setItem('session', 'abc123', { ttl: 60000 }); // expires in 1 minute
await storage.setItem('temp-data', [1, 2, 3], { ttl: 5000 }); // expires in 5 seconds
// With TTL as Date object
const expireDate = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes from now
await storage.setItem('scheduled-task', { task: 'cleanup' }, { ttl: expireDate });
// Using alias
await storage.set('config', { theme: 'dark', lang: 'en' });Retrieves a value by key, automatically handling expiration.
/**
* Retrieves a value by key, automatically handling expiration
* @param key - The key to retrieve the value for
* @returns Promise resolving to the stored value or undefined if not found/expired
*/
async function getItem(key: string): Promise<any>;
// Alias
async function get(key: string): Promise<any>;Usage Examples:
// Basic retrieval
const username = await storage.getItem('username'); // 'alice'
const user = await storage.getItem('user'); // { name: 'Alice', age: 30, active: true }
// Non-existent key returns undefined
const missing = await storage.getItem('nonexistent'); // undefined
// Expired items return undefined (and are automatically removed)
const session = await storage.getItem('session'); // undefined if TTL expired
// Using alias
const config = await storage.get('config');Updates a key's value while preserving its existing TTL, or creates a new item if the key doesn't exist or has expired.
/**
* Updates a key's value while preserving existing TTL
* @param key - The key to update
* @param value - The new value to store
* @param options - Optional configuration, can override TTL
* @returns Promise resolving to storage result
*/
async function updateItem(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;
// Alias
async function update(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;Usage Examples:
// First, set an item with TTL
await storage.setItem('user', { name: 'Alice', age: 30 }, { ttl: 3600000 }); // 1 hour
// Update preserves the original TTL
await storage.updateItem('user', { name: 'Alice', age: 31 }); // Still expires in ~1 hour
// Update with new TTL
await storage.updateItem('user', { name: 'Alice', age: 32 }, { ttl: 7200000 }); // 2 hours
// If key doesn't exist, acts like setItem
await storage.updateItem('new-key', 'new-value'); // Creates new item
// Using alias
await storage.update('user', { name: 'Alice', age: 33 });Removes an item by key, deleting it from storage.
/**
* Removes an item by key, deleting it from storage
* @param key - The key to remove
* @returns Promise resolving to removal result information
*/
async function removeItem(key: string): Promise<any>;
// Aliases
async function del(key: string): Promise<any>;
async function rm(key: string): Promise<any>;Usage Examples:
// Remove an item
await storage.removeItem('username');
// Using aliases
await storage.del('session');
await storage.rm('temp-data');
// Returns information about the removal
const result = await storage.removeItem('user');
// result: { file: '/path/to/storage/file', removed: true, existed: true }
// Removing non-existent key is safe
await storage.removeItem('nonexistent'); // No error thrownRemoves all items from storage, clearing the entire storage directory.
/**
* Removes all items from storage
* @returns Promise resolving when all items are cleared
*/
async function clear(): Promise<void>;Usage Examples:
// Clear all stored data
await storage.clear();
// Storage is now empty
const keys = await storage.keys(); // []
const length = await storage.length(); // 0TTL can be specified in several ways:
// Milliseconds from now
await storage.setItem('key', 'value', { ttl: 60000 }); // 1 minute
// Date object (absolute time)
const futureDate = new Date('2024-12-31T23:59:59Z');
await storage.setItem('key', 'value', { ttl: futureDate });
// Use default TTL from init options
await storage.init({ ttl: 3600000 }); // 1 hour default
await storage.setItem('key', 'value'); // Uses 1 hour TTL
// Disable TTL for specific item
await storage.setItem('key', 'value', { ttl: null });getItem()expiredInterval optionremoveExpiredItems() methodupdateItem() preserves existing TTL by defaultttl option in updateItem() overrides the preserved TTLupdateItem() behaves like setItem()Storage operations can throw errors in various scenarios:
try {
await storage.setItem('key', 'value');
} catch (error) {
if (error.code === 'ENOSPC') {
console.error('No space left on device');
} else if (error.code === 'EACCES') {
console.error('Permission denied');
} else {
console.error('Storage error:', error.message);
}
}Common Error Scenarios:
forgiveParseErrors: false)