@@ -94,6 +94,7 @@ Lowdb now comes with TypeScript support. You can even type `db.data` content.
94
94
type Data = {
95
95
posts: string [] // Expect posts to be an array of strings
96
96
}
97
+ const adapter = new JSONFile <Data >(' db.json' )
97
98
const db = new Low <Data >(adapter )
98
99
99
100
db .data
@@ -218,13 +219,17 @@ Synchronous adapter for `window.localStorage`.
218
219
new LowSync (new LocalStorage (name))
219
220
```
220
221
222
+ #### ` TextFile ` ` TextFileSync `
223
+
224
+ Adapters for reading and writing text. Useful for creating custom adapters.
225
+
221
226
### Third-party adapters
222
227
223
228
If you've published an adapter for lowdb, feel free to create a PR to add it here.
224
229
225
230
### Writing your own adapter
226
231
227
- You may want to create an adapter to write ` db.data ` to YAML, XML, ... or encrypt data.
232
+ You may want to create an adapter to write ` db.data ` to YAML, XML, encrypt data, a remote storage, .. .
228
233
229
234
An adapter is a simple class that just needs to expose two methods:
230
235
@@ -235,8 +240,8 @@ class AsyncAdapter {
235
240
}
236
241
237
242
class SyncAdapter {
238
- read () { /* ... */ } // data
239
- write (data ) { /* ... */ } // void
243
+ read () { /* ... */ } // should return data
244
+ write (data ) { /* ... */ } // should return nothing
240
245
}
241
246
```
242
247
@@ -267,6 +272,41 @@ const db = new Low(adapter)
267
272
268
273
See [ ` src/adapters/ ` ] ( src/adapters ) for more examples.
269
274
275
+ #### Custom serialization
276
+
277
+ To create an adapter for another format than JSON, you can use ` TextFile ` or ` TextFileSync ` .
278
+
279
+ For example:
280
+
281
+ ``` js
282
+ import { Adapter , Low , TextFile } from ' Low.js'
283
+ import YAML from ' yaml'
284
+
285
+ export class YAMLFile {
286
+ private adapter
287
+
288
+ constructor (filename : string ) {
289
+ this .adapter = new TextFile (filename)
290
+ }
291
+
292
+ async read () {
293
+ const data = await this .adapter .read ()
294
+ if (data === null ) {
295
+ return null
296
+ } else {
297
+ return YAML .parse (data)
298
+ }
299
+ }
300
+
301
+ write (obj ) {
302
+ return this .adapter .write (YAML .stringify (obj))
303
+ }
304
+ }
305
+
306
+ const adapter = new YAMLFile (' file.yaml' )
307
+ const db = new Low (adapter)
308
+ ```
309
+
270
310
## Limits
271
311
272
312
Lowdb doesn't support Node's cluster module.
0 commit comments