1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
|
# Lowdb [](http://badge.fury.io/js/lowdb) [](https://travis-ci.org/typicode/lowdb)
> A small local database for small projects :cat: (powered by lodash API)
```js
const db = low('db.json')
db.defaults({ posts: [], user: {} })
.value()
db.get('posts')
.push({ id: 1, title: 'lowdb is awesome'})
.value()
db.set('user.name', 'typicode')
.value()
```
Data is __automatically__ saved to `db.json`
```json
{
"posts": [
{ "id": 1, "title": "lowdb is awesome"}
],
"user": {
"name": "typicode"
}
}
```
And you can query it using [lodash API](https://lodash.com/docs)
```js
db.get('posts')
.find({ id: 1 })
.value()
```
Lowdb is perfect for CLIs, small servers, Electron apps and npm packages in general.
It supports __Node__, the __browser__ and uses __lodash API__, so it's very simple to learn. Actually... you may already know how to use lowdb :wink:
* [Usage examples](https://github.com/typicode/lowdb/tree/master/examples)
* [CLI](https://github.com/typicode/lowdb/tree/master/examples#cli)
* [Browser](https://github.com/typicode/lowdb/tree/master/examples#browser)
* [Server](https://github.com/typicode/lowdb/tree/master/examples#server)
* [In-memory](https://github.com/typicode/lowdb/tree/master/examples#in-memory)
* [JSFiddle live example](https://jsfiddle.net/typicode/4kd7xxbu/)
* [__Migrating from 0.12 to 0.13? See this guide.__](https://github.com/typicode/lowdb/releases/tag/v0.13.0)
## Why lowdb?
* Lodash API
* Minimal and simple to use
* Highly flexible
* __Custom storage__ (file, browser, in-memory, ...)
* __Custom format__ (JSON, BSON, YAML, XML, ...)
* Mixins (id support, ...)
* Read-only or write-only modes
* Encryption
__Important__ lowdb doesn't support Cluster.
## Install
```sh
npm install lowdb --save
yarn add lowdb # if you prefer to use yarn
```
A UMD build is also available on [unpkg](https://unpkg.com/) for testing and quick prototyping:
```html
<script src="https://unpkg.com/lodash@4/lodash.min.js"></script>
<script src="https://unpkg.com/lowdb/dist/lowdb.min.js"></script>
<script>
var db = low('db')
</script>
```
## API
__low([source, [options])__
* `source` string or null, will be passed to storage
* `options` object
* `storage` object, by default `lowdb/lib/file-sync` or `lowdb/lib/browser`.
* `read` function or null
* `write` function or null
* `format` object
* `serialize` function, by default `JSON.stringify`
* `deserialize` function, by default `JSON.parse`
* `writeOnChange`boolean
Creates a __lodash chain__, you can use __any__ lodash method on it. When `.value()` is called data is saved using `storage`.
You can use `options` to configure how lowdb should persist data. Here are some examples:
```js
// in-memory
low()
// persisted using async file storage
low('db.json', { storage: require('lowdb/lib/file-async') })
// persisted using a custom storage
low('some-source', { storage: require('./my-custom-storage') })
// write on change disabled
low('db.json', { writeOnChange: false })
// read-only
const fileSync = require('lowdb/lib/file-sync')
low('db.json', {
storage: {
read: fileSync.read
}
})
// write-only
low('db.json', {
storage: {
write: fileSync.write
}
})
```
__db.___
Database lodash instance. Use it to add your own utility functions or third-party mixins like [underscore-contrib](https://github.com/documentcloud/underscore-contrib) or [underscore-db](https://github.com/typicode/underscore-db).
```js
db._.mixin({
second: function(array) {
return array[1]
}
})
const post1 = db.get('posts').first().value()
const post2 = db.get('posts').second().value()
```
__db.getState()__
Use whenever you want to access the database state.
```js
db.getState() // { posts: [ ... ] }
```
__db.setState(newState)__
Use it to drop database or set a new state (database will be automatically persisted).
```js
const newState = {}
db.setState(newState)
```
__db.write([source])__
Persists database using `storage.write` option. Depending on the storage, it may return a promise (for example, with `file-async').
By default, lowdb automatically calls it when database changes.
```js
const db = low('db.json')
db.write() // writes to db.json
db.write('copy.json') // writes to copy.json
```
__db.read([source])__
Reads source using `storage.read` option. Depending on the storage, it may return a promise.
```js
const db = low('db.json')
db.read() // reads db.json
db.read('copy.json') // reads copy.json
```
## Guide
### How to query
With lowdb, you get access to the entire [lodash API](http://lodash.com/), so there are many ways to query and manipulate data. Here are a few examples to get you started.
Please note that data is returned by reference, this means that modifications to returned objects may change the database. To avoid such behaviour, you need to use `.cloneDeep()`.
Also, the execution of methods is lazy, that is, execution is deferred until `.value()` is called.
#### Examples
Check if posts exists.
```js
db.has('posts')
.value()
```
Set posts.
```js
db.set('posts', [])
.value()
```
Sort the top five posts.
```js
db.get('posts')
.filter({published: true})
.sortBy('views')
.take(5)
.value()
```
Get post titles.
```js
db.get('posts')
.map('title')
.value()
```
Get the number of posts.
```js
db.get('posts')
.size()
.value()
```
Get the title of first post using a path.
```js
db.get('posts[0].title')
.value()
```
Update a post.
```js
db.get('posts')
.find({ title: 'low!' })
.assign({ title: 'hi!'})
.value()
```
Remove posts.
```js
db.get('posts')
.remove({ title: 'low!' })
.value()
```
Make a deep clone of posts.
```js
db.get('posts')
.cloneDeep()
.value()
```
### How to use id based resources
Being able to get data using an id can be quite useful, particularly in servers. To add id-based resources support to lowdb, you have 2 options.
[underscore-db](https://github.com/typicode/underscore-db) provides a set of helpers for creating and manipulating id-based resources.
```js
const db = low('db.json')
db._.mixin(require('underscore-db'))
const postId = db.get('posts').insert({ title: 'low!' }).value().id
const post = db.get('posts').getById(postId).value()
```
[uuid](https://github.com/broofa/node-uuid) is more minimalist and returns a unique id that you can use when creating resources.
```js
const uuid = require('uuid')
const postId = db.get('posts').push({ id: uuid(), title: 'low!' }).value().id
const post = db.get('posts').find({ id: postId }).value()
```
### How to use a custom storage or format
`low()` accepts custom storage or format. Simply create objects with `read/write` or `serialize/deserialize` methods. See `src/browser.js` code source for a full example.
```js
const myStorage = {
read: (source, deserialize) => // must return an object or a Promise
write: (source, obj, serialize) => // must return undefined or a Promise
}
const myFormat = {
serialize: (obj) => // must return data (usually string)
deserialize: (data) => // must return an object
}
low(source, {
storage: myStorage,
format: myFormat
})
```
### How to encrypt data
Simply `encrypt` and `decrypt` data in `format.serialize` and `format.deserialize` methods.
For example, using [cryptr](https://github.com/MauriceButler/cryptr):
```js
const Cryptr = require("./cryptr"),
const cryptr = new Cryptr('my secret key')
const db = low('db.json', {
format: {
deserialize: (str) => {
const decrypted = cryptr.decrypt(str)
const obj = JSON.parse(decrypted)
return obj
},
serialize: (obj) => {
const str = JSON.stringify(obj)
const encrypted = cryptr.encrypt(str)
return encrypted
}
}
})
```
## Changelog
See changes for each version in the [release notes](https://github.com/typicode/lowdb/releases).
## Limits
lowdb is a convenient method for storing data without setting up a database server. It is fast enough and safe to be used as an embedded database.
However, if you seek high performance and scalability more than simplicity, you should probably stick to traditional databases like MongoDB.
## License
MIT - [Typicode](https://github.com/typicode)
|