0
# Core Database Classes
1
2
Core async and sync database classes that manage data with configurable storage adapters. These classes provide the fundamental database operations and serve as the foundation for all lowdb functionality.
3
4
## Capabilities
5
6
### Low Class (Async)
7
8
Main asynchronous database class for managing data with async adapters.
9
10
```typescript { .api }
11
/**
12
* Asynchronous database class for managing data with async storage adapters
13
* @template T - The type of data stored in the database
14
*/
15
class Low<T = unknown> {
16
constructor(adapter: Adapter<T>, defaultData: T);
17
18
/** Storage adapter instance */
19
adapter: Adapter<T>;
20
/** Current database data */
21
data: T;
22
23
/** Load data from adapter to memory */
24
read(): Promise<void>;
25
26
/** Save current data to adapter */
27
write(): Promise<void>;
28
29
/** Update data using a function and save automatically */
30
update(fn: (data: T) => unknown): Promise<void>;
31
}
32
```
33
34
**Usage Examples:**
35
36
```typescript
37
import { Low } from "lowdb";
38
import { JSONFile } from "lowdb/node";
39
40
type Data = {
41
users: Array<{ id: number; name: string }>;
42
settings: { theme: string };
43
};
44
45
const defaultData: Data = { users: [], settings: { theme: "light" } };
46
const adapter = new JSONFile<Data>("db.json");
47
const db = new Low<Data>(adapter, defaultData);
48
49
// Initialize database
50
await db.read();
51
52
// Direct data manipulation
53
db.data.users.push({ id: 1, name: "Alice" });
54
db.data.settings.theme = "dark";
55
await db.write();
56
57
// Update with automatic save
58
await db.update((data) => {
59
data.users.push({ id: 2, name: "Bob" });
60
data.settings.theme = "blue";
61
});
62
```
63
64
### LowSync Class (Sync)
65
66
Synchronous database class for managing data with sync adapters.
67
68
```typescript { .api }
69
/**
70
* Synchronous database class for managing data with sync storage adapters
71
* @template T - The type of data stored in the database
72
*/
73
class LowSync<T = unknown> {
74
constructor(adapter: SyncAdapter<T>, defaultData: T);
75
76
/** Storage adapter instance */
77
adapter: SyncAdapter<T>;
78
/** Current database data */
79
data: T;
80
81
/** Load data from adapter to memory synchronously */
82
read(): void;
83
84
/** Save current data to adapter synchronously */
85
write(): void;
86
87
/** Update data using a function and save automatically */
88
update(fn: (data: T) => unknown): void;
89
}
90
```
91
92
**Usage Examples:**
93
94
```typescript
95
import { LowSync } from "lowdb";
96
import { JSONFileSync } from "lowdb/node";
97
98
type Data = {
99
posts: Array<{ id: number; title: string; views: number }>;
100
};
101
102
const defaultData: Data = { posts: [] };
103
const adapter = new JSONFileSync<Data>("posts.json");
104
const db = new LowSync<Data>(adapter, defaultData);
105
106
// Initialize database
107
db.read();
108
109
// Synchronous operations
110
db.data.posts.push({ id: 1, title: "Hello World", views: 0 });
111
db.write();
112
113
// Update with automatic save
114
db.update((data) => {
115
const post = data.posts.find(p => p.id === 1);
116
if (post) post.views++;
117
});
118
```
119
120
### Adapter Interface (Async)
121
122
Interface for asynchronous storage adapters.
123
124
```typescript { .api }
125
/**
126
* Interface for asynchronous storage adapters
127
* @template T - The type of data handled by the adapter
128
*/
129
interface Adapter<T> {
130
/** Read data from storage, returns null if no data exists */
131
read(): Promise<T | null>;
132
133
/** Write data to storage */
134
write(data: T): Promise<void>;
135
}
136
```
137
138
### SyncAdapter Interface (Sync)
139
140
Interface for synchronous storage adapters.
141
142
```typescript { .api }
143
/**
144
* Interface for synchronous storage adapters
145
* @template T - The type of data handled by the adapter
146
*/
147
interface SyncAdapter<T> {
148
/** Read data from storage synchronously, returns null if no data exists */
149
read(): T | null;
150
151
/** Write data to storage synchronously */
152
write(data: T): void;
153
}
154
```
155
156
### Memory Adapters
157
158
In-memory storage adapters for testing and temporary data storage.
159
160
```typescript { .api }
161
/**
162
* In-memory async adapter for testing and temporary storage
163
* @template T - The type of data stored
164
*/
165
class Memory<T> implements Adapter<T> {
166
constructor();
167
168
read(): Promise<T | null>;
169
write(obj: T): Promise<void>;
170
}
171
172
/**
173
* In-memory sync adapter for testing and temporary storage
174
* @template T - The type of data stored
175
*/
176
class MemorySync<T> implements SyncAdapter<T> {
177
constructor();
178
179
read(): T | null;
180
write(obj: T): void;
181
}
182
```
183
184
**Usage Examples:**
185
186
```typescript
187
import { Low, LowSync, Memory, MemorySync } from "lowdb";
188
189
// Async memory adapter
190
const asyncDb = new Low(new Memory<{ count: number }>(), { count: 0 });
191
await asyncDb.read();
192
asyncDb.data.count = 42;
193
await asyncDb.write();
194
195
// Sync memory adapter
196
const syncDb = new LowSync(new MemorySync<string[]>(), []);
197
syncDb.read();
198
syncDb.data.push("hello", "world");
199
syncDb.write();
200
201
// Memory adapters are automatically used in test environments
202
// when using presets, providing isolated test data
203
```
204
205
## Data Access Patterns
206
207
### Direct Data Manipulation
208
209
Access and modify `db.data` directly, then call `write()` to persist:
210
211
```typescript
212
db.data.posts.push({ id: 1, title: "New Post" });
213
db.data.settings.theme = "dark";
214
await db.write(); // or db.write() for sync
215
```
216
217
### Update Method
218
219
Use the `update()` method for atomic operations:
220
221
```typescript
222
await db.update((data) => {
223
data.posts.push({ id: 1, title: "New Post" });
224
data.settings.theme = "dark";
225
}); // Automatically saves after function execution
226
```
227
228
### Native Array Methods
229
230
Use JavaScript's native Array methods for querying:
231
232
```typescript
233
const { posts } = db.data;
234
235
// Find operations
236
const post = posts.find(p => p.id === 1);
237
const activePosts = posts.filter(p => p.active);
238
239
// Sorting and manipulation
240
const sortedPosts = posts.toSorted((a, b) => b.views - a.views);
241
const firstPost = posts.at(0);
242
const lastPost = posts.at(-1);
243
244
// Iteration
245
posts.forEach(post => console.log(post.title));
246
const titles = posts.map(post => post.title);
247
```
248
249
## Error Handling
250
251
The core classes handle adapter-level errors by propagating them to the caller:
252
253
```typescript
254
try {
255
await db.read();
256
} catch (error) {
257
console.error("Failed to read database:", error);
258
}
259
260
try {
261
await db.write();
262
} catch (error) {
263
console.error("Failed to write database:", error);
264
}
265
```
266
267
## Type Safety
268
269
lowdb provides full TypeScript support with generic type preservation:
270
271
```typescript
272
type UserData = {
273
users: Array<{ id: number; name: string; email: string }>;
274
meta: { version: number; lastUpdated: Date };
275
};
276
277
const db = new Low<UserData>(adapter, defaultData);
278
279
// TypeScript will provide full intellisense and type checking
280
db.data.users.push({ id: 1, name: "Alice", email: "alice@example.com" }); // ✅
281
db.data.users.push({ id: 2, name: "Bob" }); // ❌ TypeScript error: missing email
282
db.data.meta.version = "1.0"; // ❌ TypeScript error: version should be number
283
```