当前位置: 代码迷 >> 综合 >> Lowdb ReadMe 中英对照
  详细解决方案

Lowdb ReadMe 中英对照

热度:92   发布时间:2023-12-27 20:22:35.0

Lowdb ReadMe

Small JSON database for Node, Electron and the browser. Powered by Lodash. ??

轻量化的基于NodeJSON文件 数据库

db.get('posts').push({
     id: 1, title: 'lowdb is awesome'}).write()

To all the amazing people who have answered the lowdb survey, thanks so much!

Usage

用法:安装

npm install lowdb
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')const adapter = new FileSync('db.json')
const db = low(adapter)// Set some defaults (required if your JSON file is empty)
//设置默认值(必需,如果你的 JSON 文件时空的
db.defaults({
     posts: [], user: {
    }, count: 0 }).write()// Add a post
db.get('posts').push({
     id: 1, title: 'lowdb is awesome'}).write()// Set a user using Lodash shorthand syntax
db.set('user.name', 'typicode').write()// Increment count
db.update('count', n => n + 1).write()

Data is saved to db.json

数据保存在 db.json 文件中

{
    "posts": [{
     "id": 1, "title": "lowdb is awesome"}],"user": {
    "name": "typicode"},"count": 1
}

You can use any of the powerful lodash functions, like _.get and _.find with shorthand syntax.

你可以使用任何强大的 lodash function ,比如_.get_.find 这样简易的语法

// For performance, use .value() instead of .write() if you're only reading from db
//如果你仅仅是想从 db 中读取数据 推荐使用 .value() 来代替 .write()
db.get('posts').find({
     id: 1 }).value()

Lowdb is perfect for CLIs, small servers, Electron apps and npm packages in general.

lowdb 非常适合CLI ,小型服务器, Electron应用程序和npm软件按包

It supports Node, the browser and uses lodash API, so it’s very simple to learn. Actually, if you know Lodash, you already know how to use lowdb ?

他支持Node ,浏览器和使用lodash API 的,因此学习起来非常简单,实际上,如果你知道lodash,那么你就知道如何使用

  • Usage examples
    • CLI
    • Browser
    • Server
    • In-memory
  • JSFiddle live example

Important lowdb doesn’t support Cluster and may have issues with very large JSON files (~200MB).

lowdb 不支持集群,可能你会遇到 大于200M的 json 文件

Install

npm install lowdb

Alternatively, if you’re using yarn

或者你可以使用 yarn :

yarn add lowdb

A UMD build is also available on unpkg for testing and quick prototyping:

在unpkg上也可以使用UMD构建进行测试和快速原型设计:

<script src="https://unpkg.com/lodash@4/lodash.min.js"></script>
<script src="https://unpkg.com/lowdb@0.17/dist/low.min.js"></script>
<script src="https://unpkg.com/lowdb@0.17/dist/LocalStorage.min.js"></script>
<script>var adapter = new LocalStorage('db')var db = low(adapter) </script>

API

low(adapter)

Returns a lodash chain with additional properties and functions described below.

返回一个lodash链,其中包含下面描述的其他属性和函数。

db.[…].write() and db.[…].value()

write() writes database to state. 将数据库写入

On the other hand, value() is just _.prototype.value() and should be used to execute a chain that doesn’t change database state.

另一方面,value()只是_.prototype.value()并且应该用于执行不更改数据库状态的链。

db.set('user.name', 'typicode').write()

Please note that db.[...].write() is syntactic sugar and equivalent to

请注意,这db.[...].write()是语法糖和相当于

db.set('user.name', 'typicode').value()db.write()

db._

Database lodash instance. Use it to add your own utility functions or third-party mixins like underscore-contrib or lodash-id.

数据库lodash实例。使用它来添加自己的实用程序函数或第三方mixins,如underscore-contrib或lodash-id

db._.mixin({
    second: function(array) {
    return array[1]}
})db.get('posts').second().value()

db.getState()

Returns database state. 返回数据库状态

db.getState() // { posts: [ ... ] }

db.setState(newState)

Replaces database state. 替换数据库状态。

const newState = {
    }
db.setState(newState)

db.write()

Persists database using adapter.write (depending on the adapter, may return a promise).

使用持久化数据库adapter.write(取决于adapter,可能会返回一个promise)

// With lowdb/adapters/FileSync
//使用lowdb / adapters / FileSync
db.write()
console.log('State has been saved')// With lowdb/adapters/FileAsync
使用lowdb / adapters / FileAsync
db.write().then(() => console.log('State has been saved'))

db.read()

Reads source using storage.read option (depending on the adapter, may return a promise).

使用storage.read选项读取源代码(取决于adapter,可能会返回一个promise)

// With lowdb/FileSync
//使用lowdb / FileSync
db.read()
console.log('State has been updated')// With lowdb/FileAsync
//使用lowdb / FileAsync
db.read().then(() => console.log('State has been updated'))

Adapters API

Please note this only applies to adapters bundled with Lowdb. Third-party adapters may have different options.

请注意,这仅适用于与Lowdb捆绑在一起的适配器。第三方适配器可能有不同的选项。

For convenience, FileSync, FileAsync and LocalBrowser accept the following options:

为了方便,FileSyncFileAsyncLocalBrowser接受以下选项:

  • defaultValue if file doesn’t exist, this value will be used to set the initial state (default: {})

    默认值如果文件不存在,则该值将被用于设定初始状态(默认值:{}

  • serialize/deserialize functions used before writing and after reading (default: JSON.stringify and JSON.parse)

    序列化/反序列化在写入之前和读取之后使用的函数(默认值:JSON.stringifyJSON.parse )

const adapter = new FileSync('array.yaml', {
    defaultValue: [],serialize: (array) => toYamlString(array),deserialize: (string) => fromYamlString(string)
})

Guide

How to query

如何查询

With lowdb, you get access to the entire lodash API, so there are many ways to query and manipulate data. Here are a few examples to get you started.

使用lowdb,您可以访问整个lodash API,因此有许多方法可以查询和操作数据。以下是一些可以帮助您入门的示例。

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().

请注意,数据是通过引用返回的,这意味着对返回对象的修改可能会更改数据库。要避免此类行为,您需要使用.cloneDeep()

Also, the execution of methods is lazy, that is, execution is deferred until .value() or .write() is called.

此外,方法的执行是惰性的,意味着延迟执行直到.value().write()被调用。

Reading from existing JSON file

从现有的JSON文件中读取

If you are reading from a file adapter, the path is relative to execution path (CWD) and not to your code.

如果从file adaapter读取,则路径相对于执行路径(CWD)而不是代码。

my_project/src/my_example.jsdb.json 

So then you read it like this:

接下来你可以这样读

// file src/my_example.js
//文件 src/my_example.js
const adapter = new FileSync('db.json')// With lowdb/FileAsync
//使用 lowdb/FileAsync
db.read().then(() => console.log('Content of my_project/db.json is loaded'))

Examples

Check if posts exists.

检查 posts 是否存在

db.has('posts').value()

Set posts.

设置 posts

db.set('posts', []).write()

Sort the top five posts.

排序前5的posts

db.get('posts').filter({
    published: true}).sortBy('views').take(5).value()

Get post titles.

获得 posts的标题

db.get('posts').map('title').value()

Get the number of posts.

获得posts的数目

db.get('posts').size().value()

Get the title of first post using a path.

通过路径获取第一个post的标题

db.get('posts[0].title').value()

Update a post.

更新post

db.get('posts').find({
     title: 'low!' }).assign({
     title: 'hi!'}).write()

Remove posts.

移除posts

db.get('posts').remove({
     title: 'low!' }).write()

Remove a property.

移除一个属性

db.unset('user.name').write()

Make a deep clone of posts.

对posts进行深度克隆

db.get('posts').cloneDeep().value()

How to use id based resources

如何使用基于id的资源

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.

能够使用id获取数据非常有用,尤其是在服务器中。要为lowdb添加基于id的资源支持,您有2个选项。

shortid is more minimalist and returns a unique id that you can use when creating resources.

shortid更简约,并返回在创建资源时可以使用的唯一ID。

const shortid = require('shortid')const postId = db.get('posts').push({
     id: shortid.generate(), title: 'low!' }).write().idconst post = db.get('posts').find({
     id: postId }).value()

lodash-id provides a set of helpers for creating and manipulating id-based resources.

lodash-id提供了一组帮助程序,用于创建和操作基于id的资源。

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...
//插入一个新post
const newPost = collection.insert({
     title: 'low!' }).write()// ...and retrieve it using its id
//通过ID检索
const post = collection.getById(newPost.id).value()

How to create custom adapters

如何创建自定义adapters

low() accepts custom Adapter, so you can virtually save your data to any storage using any format.

low() 接受自定义adapter,因此您可以使用任何格式将数据完全地保存到任何形式存储。

class MyStorage {
    constructor() {
    // ...}read() {
    // Should return data (object or array) or a Promise//应返回数据(对象或数组)或 一个 Promise}write(data) {
    // Should return nothing or a Promise//返回一个 Promise 或者空}
}const adapter = new MyStorage(args)
const db = low()

See src/adapters for examples.

有关示例,请参阅src / adapters。

How to encrypt data

如何加密数据

FileSync, FileAsync and LocalStorage accept custom serialize and deserialize functions. You can use them to add encryption logic.

FileSyncFileAsyncLocalStorage接受自定义serializedeserialize功能。您可以使用它们来添加加密逻辑。

const adapter = new FileSync('db.json', {
    serialize: (data) => encrypt(JSON.stringify(data)),deserialize: (data) => JSON.parse(decrypt(data))
})

Changelog

更新日志

See changes for each version in the release notes.

请参阅发行说明中每个版本的更改。

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.

Lowdb是一种在不设置数据库服务器的情况下存储数据的便捷方法。它足够快且可以用作嵌入式数据库。但是,如果您寻求高性能和可扩展性而不是简单性,那么您应该坚持使用像MongoDB这样的传统数据库。

License

MIT - Typicode ?

(所有权利归原作者所有 下载自github:https://github.com/typicode/lowdb)

  相关解决方案