本文目錄一覽:
LowDB 輕量級 JSON 本地數據庫
作為輕量級的本地存儲方式,對於構建不依賴服務器的小型項目,用LowDB存儲和管理數據是十分理想的選擇。在Nodejs, Electron and browser等一些小型項目中經常能看到LowDB的身影。
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()
函數 功能
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()
針對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))
})
可以直接使用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()
可以使用 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()
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);
==============================================
英文官網介紹,更加簡潔
Lowdb 3 is a pure ESM package. If you’re having trouble importing it in your project, please read this.
You can use TypeScript to type check your data.
You can also add lodash or other utility libraries to improve lowdb.
For CLI, server and browser usage, see examples/ directory.
Lowdb has two classes (for asynchronous and synchronous adapters).
Calls adapter.read() and sets db.data .
Note: JSONFile and JSONFileSync adapters will set db.data to null if file doesn’t exist.
Calls adapter.write(db.data) .
Holds your db content. If you’re using the adapters coming with lowdb, it can be any type supported by JSON.stringify .
For example:
Adapters for reading and writing JSON files.
In-memory adapters. Useful for speeding up unit tests.
Synchronous adapter for window.localStorage .
Adapters for reading and writing text. Useful for creating custom adapters.
If you’ve published an adapter for lowdb, feel free to create a PR to add it here.
You may want to create an adapter to write db.data to YAML, XML, encrypt data, a remote storage, …
An adapter is a simple class that just needs to expose two methods:
For example, let’s say you have some async storage and want to create an adapter for it:
See src/adapters/ for more examples.
To create an adapter for another format than JSON, you can use TextFile or TextFileSync .
For example:
Lowdb doesn’t support Node’s cluster module.
If you have large JavaScript objects ( ~10-100MB ) you may hit some performance issues. This is because whenever you call db.write , the whole db.data is serialized using JSON.stringify and written to storage.
Depending on your use case, this can be fine or not. It can be mitigated by doing batch operations and calling db.write only when you need it.
If you plan to scale, it’s highly recommended to use databases like PostgreSQL or MongoDB instead.
json是不是相當於我們的數據庫
json不是一種文件傳輸的格式嗎。。。。是我記錯了嘛。。。(⊙o⊙)… 就像xml,正則表達式那樣的數據格式
json是什麼意思
json的意思就是一種輕量級的數據交換格式。其中的具體情況如下:
它基於ECMAScript (歐洲計算機協會制定的js規範)的一個子集,採用完全獨立於編程語言的文本格式來存儲和表示數據。
簡潔和清晰的層次結構使得json成為理想的數據交換語言,易於人閱讀和編寫,同時也易於機器解析和生成,並有效地提升網絡傳輸效率。
擴展資料
據了解,json的交互方式主要分為:
1、同步交互
發送一個請求,需要等待返回,然後才能夠發送下一個請求,有個等待過程;
2、異步交互
發送一個請求,不需要等待返回,隨時可以再發送下一個請求,即不需要等待。
由此看來,區別在於一個需要等待,一個不需要等待,在部分情況下,項目開發中都會優先選擇不需要等待的異步交互方式。
原創文章,作者:YLCZ,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/141571.html