0
# Initialization and Configuration
1
2
Essential setup methods for configuring node-persist storage behavior, directory paths, serialization options, TTL defaults, and performance settings.
3
4
## Capabilities
5
6
### Async Initialization
7
8
Initializes the default storage instance asynchronously, creating the storage directory if needed.
9
10
```javascript { .api }
11
/**
12
* Initializes the default storage instance asynchronously
13
* @param options - Configuration options for storage behavior
14
* @returns Promise resolving to the applied options
15
*/
16
async function init(options?: StorageOptions): Promise<StorageOptions>;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
const storage = require('node-persist');
23
24
// Basic initialization with default options
25
await storage.init();
26
27
// Initialize with custom directory
28
await storage.init({
29
dir: './my-storage',
30
logging: true
31
});
32
33
// Initialize with TTL and custom serialization
34
await storage.init({
35
dir: '/tmp/cache',
36
ttl: 24 * 60 * 60 * 1000, // 24 hours
37
stringify: JSON.stringify,
38
parse: JSON.parse,
39
encoding: 'utf8'
40
});
41
```
42
43
### Synchronous Initialization
44
45
Initializes the default storage instance synchronously, creating the storage directory if needed.
46
47
```javascript { .api }
48
/**
49
* Initializes the default storage instance synchronously
50
* @param options - Configuration options for storage behavior
51
* @returns The applied options object
52
*/
53
function initSync(options?: StorageOptions): StorageOptions;
54
```
55
56
**Usage Examples:**
57
58
```javascript
59
const storage = require('node-persist');
60
61
// Synchronous initialization
62
storage.initSync({
63
dir: './sync-storage',
64
ttl: 60000 // 1 minute TTL
65
});
66
67
// Can immediately use storage methods after initSync
68
await storage.setItem('key', 'value');
69
```
70
71
### Storage Instance Factory
72
73
Creates a new LocalStorage instance with optional configuration (useful for multiple storage locations).
74
75
```javascript { .api }
76
/**
77
* Creates a new LocalStorage instance with optional configuration
78
* @param options - Configuration options for the new instance
79
* @returns New LocalStorage instance (must still call init)
80
*/
81
function create(options?: StorageOptions): LocalStorage;
82
```
83
84
**Usage Examples:**
85
86
```javascript
87
const storage = require('node-persist');
88
89
// Create separate storage instances
90
const userStorage = storage.create({ dir: './users' });
91
const sessionStorage = storage.create({ dir: './sessions', ttl: 3600000 });
92
93
// Initialize each instance
94
await userStorage.init();
95
await sessionStorage.init();
96
97
// Use independently
98
await userStorage.setItem('user1', { name: 'Alice' });
99
await sessionStorage.setItem('session1', 'abc123');
100
```
101
102
### Configuration Options
103
104
Complete configuration interface with all available options and their defaults.
105
106
```javascript { .api }
107
interface StorageOptions {
108
/** Storage directory path (relative or absolute) */
109
dir?: string; // default: '.node-persist/storage'
110
111
/** Function to serialize objects to strings */
112
stringify?: (obj: any) => string; // default: JSON.stringify
113
114
/** Function to parse strings back to objects */
115
parse?: (str: string) => any; // default: JSON.parse
116
117
/** File encoding for storage files */
118
encoding?: string; // default: 'utf8'
119
120
/** Enable logging (boolean) or provide custom logging function */
121
logging?: boolean | Function; // default: false
122
123
/** Default TTL in milliseconds, or true for 24h default */
124
ttl?: number | boolean; // default: false
125
126
/** Interval for automatic expired item cleanup (milliseconds) */
127
expiredInterval?: number; // default: 120000 (2 minutes)
128
129
/** Ignore corrupted storage files instead of throwing errors */
130
forgiveParseErrors?: boolean; // default: false
131
132
/** Use write queue for better performance and consistency */
133
writeQueue?: boolean; // default: true
134
135
/** How often to process write queue (milliseconds) */
136
writeQueueIntervalMs?: number; // default: 1000
137
138
/** Only write the last value when multiple writes to same key */
139
writeQueueWriteOnlyLast?: boolean; // default: true
140
141
/** Limit concurrent file descriptors to avoid EMFILE errors */
142
maxFileDescriptors?: number; // default: Infinity
143
}
144
```
145
146
**Common Configuration Patterns:**
147
148
```javascript
149
// High-performance caching setup
150
await storage.init({
151
dir: '/tmp/app-cache',
152
ttl: 3600000, // 1 hour
153
writeQueue: true,
154
writeQueueWriteOnlyLast: true,
155
maxFileDescriptors: 256,
156
expiredInterval: 300000 // 5 minutes
157
});
158
159
// Development/debugging setup
160
await storage.init({
161
dir: './dev-storage',
162
logging: true,
163
forgiveParseErrors: true,
164
writeQueue: false // immediate writes for debugging
165
});
166
167
// Production setup with custom serialization
168
await storage.init({
169
dir: process.env.STORAGE_DIR || './production-storage',
170
ttl: false, // no default TTL
171
expiredInterval: 600000, // 10 minutes
172
maxFileDescriptors: 512,
173
stringify: (obj) => JSON.stringify(obj, null, 0),
174
parse: JSON.parse,
175
logging: (msg) => console.log(`[storage] ${msg}`)
176
});
177
```
178
179
### Storage Directory Management
180
181
The storage directory is automatically created if it doesn't exist. Directory paths can be relative (to current working directory) or absolute.
182
183
**Directory Path Resolution:**
184
- Relative paths: resolved relative to `process.cwd()`
185
- Absolute paths: used as-is
186
- Default: `.node-persist/storage` (relative to current working directory)
187
188
**Important Notes:**
189
- The storage directory should only contain files created by node-persist
190
- Setting `forgiveParseErrors: true` allows the presence of non-storage files
191
- Each storage instance should use a separate directory to avoid conflicts