作为轻量级的本地存储方式,对于构建不依赖服务器的小型项目,用LowDB存储和管理数据是十分理想的选择。在Nodejs, Electron and browser等一些小型项目中经常能看到LowDB的身影。
https://github.com/typicode/lowdb
1. 使用方式
npm install lowdb 或者: yarn add lowdb
const low = require('lowdb'); const FileSync = require('lowdb/adapters/FileSync'); // 有多种适配器可选择 const adapter = new FileSync('db.json'); // 申明一个适配器 const db = low(adapter); db.defaults({posts: [], user: {}, count: 0}) .write(); db.get('posts') .push({id: 1, title: 'lowdb is awesome'}) .write() db.set('user.name', 'typicode') .write() db.update('count', n => n + 1) .write()
运行程序会在项目中添加db.json文件,里面存储了添加的数据:
{ "posts": [ { "id": 1, "title": "lowdb is awesome" } ], "user": { "name": "typicode" }, "count": 1 }
lowdb是基于lodash构建的,所以可以使用任何lodash强大的函数,比如: _.get() 和 _.find(),并且可以串联地使用:
db.get('users') .find({sex: 'male'}) .value()
2. API
函数 | 功能 |
low(adapter) | 返回一个具有特定属性和功能的 lodash chain |
db.[…].write() / .value() | 写 / 读数据 |
db.getState() / .setState() | 获取 / 设置数据库的状态 |
db._ | 数据库lodash的实例,可以利用这个添加自己的函数或者第三方的mixins,比如lodash-id |
db._.mixin({ second: function(array) { return array[1] } }) db.get('posts') .second() .value()
3. Adapters API
针对lowdb自带的适配器:FileSync、FileAsync 和 LocalBrowser,有以下可选参数:
defaultValue: 文件不存在时的默认值;
serialize/deserialize: 写之前和读之后的操作。
const adapter = new FilSync('db.json',{ serialize: (data) => encrypt(JSON.stringify(data)), deserialize: (data) => JSON.parse(decrypt(data)) })
4. 查询
可以直接使用lodash的函数进行查询。需要注意的是有些操作可能会导致原数据被修改,为了避免这种误操作,需要使用 .cloneDeep(),操作都是惰性的,只有调用 .value()或 .write()后才会正式执行。
检查users是是否存在
db.has('users') .value()
设置users
db.set('users', []) .write()
排序、选择
db.get('users') .filter({sex: 'male'}) .sortBy('age') .take(5) .value()
获取特定字段
db.get('users') .map('name') .value()
获取数量
db.get('users') .size() .value()
获取特定信息
db.get('users[0].name') .value()
更新信息
db.get('users') .find({name: 'Tom'}) .assign({name: 'Tim'}) .write()
删除信息
db.get('users') .remove({name: 'Time'}) .write()
移除属性
db.unset('users.name) .write()
深拷贝
db.get('users') .cloneDeep() .value()
5. 使用id索引
可以使用 shortid 和 lodash-id 为数据库中的每一条记录创建唯一的id索引,然后通过id检索操作记录:
const shortid = require('shortid') const postId = db .get('posts') .push({ id: shortid.generate(), title: 'low!' }) .write() .id const post = db .get('posts') .find({ id: postId }) .value()
const lodashId = require('lodash-id') const FileSync = require('lowdb/adapters/FileSync') const adapter = new FileSync('db.json') const db = low(adapter) db._.mixin(lodashId) // We need to set some default values, if the collection does not exist yet // We also can store our collection const collection = db .defaults({ posts: [] }) .get('posts') // Insert a new post... const newPost = collection .insert({ title: 'low!' }) .write() // ...and retrieve it using its id const post = collection .getById(newPost.id) .value()
6. 自定义Adapter
low( ) 函数接受自定义的Adapter
class MyStorage { constructor() { // ... } read() { // Should return data (object or array) or a Promise } write(data) { // Should return nothing or a Promise } } const adapter = new MyStorage(args) const db = low(adapter);
评论前必须登录!
注册