0
# node-persist
1
2
node-persist provides super-easy (and fast) persistent data structures in Node.js, modeled after HTML5 localStorage. It stores data as JSON documents in the file system instead of using a database, offering high performance with minimal network overhead. The library supports asynchronous operations with async/await patterns, includes TTL (time-to-live) functionality for automatic data expiration, and provides comprehensive data management capabilities.
3
4
## Package Information
5
6
- **Package Name**: node-persist
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install node-persist`
10
11
## Core Imports
12
13
```javascript
14
const storage = require('node-persist');
15
```
16
17
## Basic Usage
18
19
```javascript
20
const storage = require('node-persist');
21
22
// Initialize storage (required before use)
23
await storage.init();
24
25
// Store and retrieve data
26
await storage.setItem('user', { name: 'Alice', age: 30 });
27
const user = await storage.getItem('user');
28
console.log(user); // { name: 'Alice', age: 30 }
29
30
// Use with TTL (time-to-live)
31
await storage.setItem('session', 'abc123', { ttl: 60000 }); // expires in 1 minute
32
```
33
34
## Architecture
35
36
node-persist is built around several key components:
37
38
- **LocalStorage Class**: Core storage implementation providing all persistence operations
39
- **Main Module**: Factory and convenience wrapper exposing a default instance and factory methods
40
- **Method Mixin**: After calling `init()` or `initSync()`, all LocalStorage methods are mixed into the main module for direct access
41
- **File-based Storage**: Uses filesystem with SHA256-hashed filenames for key storage
42
- **Write Queue**: Batched write operations for improved performance and data consistency
43
- **TTL Management**: Automatic expiration and cleanup of time-limited data
44
- **Async/Await API**: Modern promise-based interface throughout
45
46
## Capabilities
47
48
### Initialization and Configuration
49
50
Essential setup methods for configuring storage behavior, directory paths, serialization options, TTL defaults, and performance settings.
51
52
```javascript { .api }
53
async function init(options?: StorageOptions): Promise<StorageOptions>;
54
function initSync(options?: StorageOptions): StorageOptions;
55
function create(options?: StorageOptions): LocalStorage;
56
57
// After init, ALL LocalStorage methods are mixed into the main module:
58
function setOptions(options: StorageOptions): void;
59
60
interface StorageOptions {
61
dir?: string;
62
stringify?: (obj: any) => string;
63
parse?: (str: string) => any;
64
encoding?: string;
65
logging?: boolean | Function;
66
ttl?: number | boolean;
67
expiredInterval?: number;
68
forgiveParseErrors?: boolean;
69
writeQueue?: boolean;
70
writeQueueIntervalMs?: number;
71
writeQueueWriteOnlyLast?: boolean;
72
maxFileDescriptors?: number;
73
}
74
```
75
76
[Initialization and Configuration](./initialization.md)
77
78
### Data Storage Operations
79
80
Core persistence operations for storing, retrieving, updating, and removing data with optional TTL support.
81
82
```javascript { .api }
83
async function setItem(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;
84
async function getItem(key: string): Promise<any>;
85
async function updateItem(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;
86
async function removeItem(key: string): Promise<any>;
87
async function clear(): Promise<void>;
88
89
// Aliases
90
async function set(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;
91
async function get(key: string): Promise<any>;
92
async function update(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;
93
async function del(key: string): Promise<any>;
94
async function rm(key: string): Promise<any>;
95
```
96
97
[Data Storage Operations](./storage-operations.md)
98
99
### Data Query and Inspection
100
101
Methods for querying stored data, retrieving keys and values, and inspecting storage contents with filtering capabilities.
102
103
```javascript { .api }
104
async function keys(filter?: (datum: any) => boolean): Promise<string[]>;
105
async function values(filter?: (datum: any) => boolean): Promise<any[]>;
106
async function length(filter?: (datum: any) => boolean): Promise<number>;
107
function valuesWithKeyMatch(match: string | RegExp): Promise<any[]>;
108
async function forEach(callback: (datum: { key: string, value: any }) => Promise<void>): Promise<void>;
109
function data(): Promise<Array<{ key: string, value: any, ttl?: number }>>;
110
111
// Low-level data access (also mixed into main module after init):
112
function getDatum(key: string): Promise<any>;
113
function getRawDatum(key: string): Promise<string>;
114
async function getDatumValue(key: string): Promise<any>;
115
function getDatumPath(key: string): string; // synchronous
116
117
// Utility methods (also mixed into main module after init):
118
async function removeExpiredItems(): Promise<void>;
119
function startExpiredKeysInterval(): void;
120
function stopExpiredKeysInterval(): void;
121
function startWriteQueueInterval(): void;
122
function stopWriteQueueInterval(): void;
123
```
124
125
[Data Query and Inspection](./query-operations.md)
126
127
### Low-level Operations and Utilities
128
129
Advanced methods for direct data access, manual expiration management, and internal storage operations.
130
131
```javascript { .api }
132
function getDatum(key: string): Promise<any>;
133
function getRawDatum(key: string): Promise<string>;
134
async function getDatumValue(key: string): Promise<any>;
135
function getDatumPath(key: string): string;
136
137
async function removeExpiredItems(): Promise<void>;
138
function startExpiredKeysInterval(): void;
139
function stopExpiredKeysInterval(): void;
140
function startWriteQueueInterval(): void;
141
function stopWriteQueueInterval(): void;
142
function setOptions(options: StorageOptions): void;
143
```
144
145
[Low-level Operations and Utilities](./low-level-operations.md)
146
147
## Types
148
149
```javascript { .api }
150
class LocalStorage {
151
constructor(options?: StorageOptions);
152
async init(options?: StorageOptions): Promise<StorageOptions>;
153
initSync(options?: StorageOptions): StorageOptions;
154
setOptions(options: StorageOptions): void;
155
156
// All storage operations are available as methods
157
async setItem(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;
158
async getItem(key: string): Promise<any>;
159
async updateItem(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;
160
async removeItem(key: string): Promise<any>;
161
async clear(): Promise<void>;
162
163
// Query methods
164
async keys(filter?: Function): Promise<string[]>;
165
async values(filter?: Function): Promise<any[]>;
166
async length(filter?: Function): Promise<number>;
167
valuesWithKeyMatch(match: string | RegExp): Promise<any[]>;
168
async forEach(callback: Function): Promise<void>;
169
170
// Low-level access
171
data(): Promise<any[]>;
172
getDatum(key: string): Promise<any>;
173
getRawDatum(key: string): Promise<string>;
174
async getDatumValue(key: string): Promise<any>;
175
getDatumPath(key: string): string; // synchronous
176
177
// Utility methods
178
async removeExpiredItems(): Promise<void>;
179
startExpiredKeysInterval(): void;
180
stopExpiredKeysInterval(): void;
181
startWriteQueueInterval(): void;
182
stopWriteQueueInterval(): void;
183
}
184
185
interface StorageOptions {
186
dir?: string;
187
stringify?: (obj: any) => string;
188
parse?: (str: string) => any;
189
encoding?: string;
190
logging?: boolean | Function;
191
ttl?: number | boolean;
192
expiredInterval?: number;
193
forgiveParseErrors?: boolean;
194
writeQueue?: boolean;
195
writeQueueIntervalMs?: number;
196
writeQueueWriteOnlyLast?: boolean;
197
maxFileDescriptors?: number;
198
}
199
```