# @commonify/lowdb 中文文档

规范地址：https://npmcn.com/package/%40commonify/lowdb/

版本：3\.0\.0
npm 元数据更新时间：2022-04-05T00:31:49.255Z
中文译文更新时间：2026-11-10T12:26:03.627Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40commonify/lowdb
原文对照：https://npmcn.com/package/%40commonify/lowdb/?lang=original
项目主页：https://github.com/typicode/lowdb#readme
源码仓库：https://github.com/typicode/lowdb

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：30.3 kB，25 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：^12\.20\.0 \|\| ^14\.13\.1 \|\| \>=16\.0\.0
- 运行依赖：1 个
- 首次发布：2022-01-24T08:25:15.304Z
- 最新版本发布：2022-01-24T08:25:15.522Z
- 近 30 天下载量：4217（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：1（近 12 个月 0 个）

## 中文简介

CommunityJS版本的低分b 3.0.0. 见 [https://github.com/mifi/compublicify (中文(简体) )](https://github.com/mifi/commonify)

## 安装

```sh
npm install @commonify/lowdb
```

也可以使用：`pnpm add @commonify/lowdb`、`yarn add @commonify/lowdb`、`bun add @commonify/lowdb`

## README

# 低分数b [![](http://img.shields.io/npm/dm/lowdb.svg?style=flat)](https://www.npmjs.org/package/lowdb) [![Node.js CI](https://github.com/typicode/lowdb/actions/workflows/node.js.yml/badge.svg)](https://github.com/typicode/lowdb/actions/workflows/node.js.yml)

> 小项目的本地 JSON 数据库

```js
// This is pure JS, not specific to lowdb ;)
db.data.posts.push({ id: 1, title: 'lowdb is awesome' })

// Save to file
db.write()
```

```js
// db.json
{
  "posts": [
    { "id": 1, "title": "lowdb is awesome" }
  ]
}
```

如果你喜欢"低",请参看 [页:1](https://github.com/typicode/xv) (试验跑道)和 [斯蒂诺](https://github.com/typicode/steno) (快速文件撰写器).

## 发起人

  
  

[![](https://jsonplaceholder.typicode.com/mockend.svg)](https://mockend.com/)

  
  

[成为赞助商,在这里有你的公司标志](https://github.com/sponsors/typicode)。 。 。 .

请帮我建立OSS [GitHub 赞助商](https://github.com/sponsors/typicode)

## 特征

-   **轻巧**
-   **最小数** 并且容易学习API
-   使用 **普通联署材料**
-   改进 **类型脚本** 支助
-   原子写入
-   可隐藏 :
    -   更改存储, 文件格式( JSON, YAML,...) 或通过 添加加密 [适配器](https://npmcn.com/package/%40commonify/lowdb/#readme-adapters)
    -   加入罗达斯,拉姆达,... 超级大国!

## 安装

```sh
npm install lowdb
```

## 使用量

_Lowdb 2是一个纯粹的无害环境管理包. 如果你在你的项目里 进口有问题,请 [读取此](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c)。 。 。 ._

```js
import { join, dirname } from 'path'
import { Low, JSONFile } from 'lowdb'
import { fileURLToPath } from 'url'

const __dirname = dirname(fileURLToPath(import.meta.url));

// Use JSON file for storage
const file = join(__dirname, 'db.json')
const adapter = new JSONFile(file)
const db = new Low(adapter)

// Read data from JSON file, this will set db.data content
await db.read()

// If file.json doesn't exist, db.data will be null
// Set default data
db.data ||= { posts: [] }
// db.data = db.data || { posts: [] } // for node < v15.x

// Create and query items using plain JS
db.data.posts.push('hello world')
db.data.posts[0]

// You can also use this syntax if you prefer
const { posts } = db.data
posts.push('hello world')

// Write db.data content to db.json
await db.write()
```

```js
// db.json
{
  "posts": [ "hello world" ]
}
```

### 类型脚本

Lowdb现在带有 TypeScript 支持. 您甚至可以输入 `db.data` 内容.

```ts
type Data = {
  posts: string[] // Expect posts to be an array of strings
}
const adapter = new JSONFile<Data>('db.json')
const db = new Low<Data>(adapter)

db.data
  .posts
  .push(1) // TypeScript error 🎉
```

### 洛达什

方便地添加lodash或其他公用库来改进lowdb.

```js
import lodash from 'lodash'

// ...
// Note: db.data needs to be initialized before lodash.chain is called.
db.chain = lodash.chain(db.data)

// Instead of db.data, you can now use db.chain if you want to use the powerful API that lodash provides
const post = db.chain
  .get('posts')
  .find({ id: 1 })
  .value() // Important: value() needs to be called to execute chain
```

### 更多实例

关于CLI、服务器和浏览器的使用,见 [`examples/`](https://npmcn.com/examples) 目录.

## API 密码

### 类

Lowdb有两个类(用于同步和同步适配器).

#### `new Low(adapter)`

```js
import { Low, JSONFile } from 'lowdb'

const db = new Low(new JSONFile('file.json'))
await db.read()
await db.write()
```

#### `new LowSync(adapterSync)`

```js
import { LowSync, JSONFileSync } from 'lowdb'

const db = new LowSync(new JSONFileSync('file.json'))
db.read()
db.write()
```

### 方法

#### `db.read()`

电话 `adapter.read()` 组合 `db.data`。 。 。 .

**说明:** `JSONFile` 财务报告和审定财务报表 `JSONFileSync` 适配器将设置 `db.data` 改为 `null` 如果文件不存在的话.

```js
db.data // === null
db.read()
db.data // !== null
```

#### `db.write()`

电话 `adapter.write(db.data)`。 。 。 .

```js
db.data = { posts: [] }
db.write() // file.json will be { posts: [] }
db.data = {}
db.write() // file.json will be {}
```

### 属性

#### `db.data`

保持你的DB内容。 如果你使用适配器 与低分量, 它可以是任何类型支持 [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)。 。 。 .

例如:

```js
db.data = 'string'
db.data = [1, 2, 3]
db.data = { key: 'value' }
```

## 适配器

### 低维适配器

#### `JSONFile` `JSONFileSync`

用于读取并撰写JSON文件的适配器.

```js
new Low(new JSONFile(filename))
new LowSync(new JSONFileSync(filename))
```

#### `Memory` `MemorySync`

内相相适者. 用来加速单位测试.

```js
new Low(new Memory())
new LowSync(new MemorySync())
```

#### `LocalStorage`

同步适配器 `window.localStorage`。 。 。 .

```js
new LowSync(new LocalStorage(name))
```

#### `TextFile` `TextFileSync`

读写文字的适配器. 用于创建自定义适配器 .

### 第三方适配器

如果你已经发布了一个适配器的Lowdb, 请随意创建 PR 添加到这里.

### 写入自己的适配器

您可能想要创建一个适配器来写入 `db.data` 到YAML,XML,加密数据,远程存储,.

适配器是一个简单的类,只需要暴露出两种方法:

```js
class AsyncAdapter {
  read() { /* ... */ } // should return Promise<data>
  write(data) { /* ... */ } // should return Promise<void>
}

class SyncAdapter {
  read() { /* ... */ } // should return data
  write(data) { /* ... */ } // should return nothing
}
```

例如,让我们假设你有一些同位素存储器,并想为此创建一个适配器:

```js
import { api } from './AsyncStorage'

class CustomAsyncAdapter {
  // Optional: your adapter can take arguments
  constructor(args) {
    // ...
  }

  async read() {
    const data = await api.read()
    return data
  }

  async write(data) {
    await api.write(data)
  }
}

const adapter = new CustomAsyncAdapter()
const db = new Low(adapter)
```

见 [`src/adapters/`](https://npmcn.com/package/%40commonify/lowdb/src/adapters) 需要更多的实例.

#### 自定义序列化

要为 JSON 以外的格式创建适配器, 您可以使用 `TextFile` 或者说 `TextFileSync`。 。 。 .

例如:

```js
import { Adapter, Low, TextFile } from 'lowdb'
import YAML from 'yaml'

class YAMLFile {
  constructor(filename) {
    this.adapter = new TextFile(filename)
  }

  async read() {
    const data = await this.adapter.read()
    if (data === null) {
      return null
    } else {
      return YAML.parse(data)
    }
  }

  write(obj) {
    return this.adapter.write(YAML.stringify(obj))
  }
}

const adapter = new YAMLFile('file.yaml')
const db = new Low(adapter)
```

## 限制

Lowdb不支持Node的集群模块.

如果您有大型 JavaScript 对象(`~10-100MB`你可能会遇到一些表现问题。 因为每当你打电话 `db.write`整个 `db.data` 被序列化并写入存储.

这取决于你的用法, 这可以是罚款与否。 可以通过批量操作和呼叫来缓解 `db.write` 只有当你需要它.

如果你计划规模化,则高度推荐使用PostgreSQL,MongoDB等数据库. .

## 常见问题

### @commonify/lowdb 是什么？

CommunityJS版本的低分b 3\.0\.0\. 见 https://github\.com/mifi/compublicify \(中文\(简体\) \)

### 如何安装 @commonify/lowdb？

在项目目录运行 npm install @commonify/lowdb，或使用 pnpm add / yarn add / bun add。

### @commonify/lowdb 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @commonify/lowdb 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @commonify/lowdb 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js ^12\.20\.0 \|\| ^14\.13\.1 \|\| \>=16\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @commonify/lowdb 可以商用吗？

@commonify/lowdb 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @commonify/lowdb 的下载量有多少？

根据 npm 官方下载统计，@commonify/lowdb 在 2026/10/11 – 2026/11/09 这 30 天内被下载 4,217 次，日均约 141 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @commonify/lowdb 还在维护吗？

最新版本 3\.0\.0 发布于 2022/01/24（4 年前）；至今共发布 1 个版本，其中过去 12 个月发布了 0 个；首次发布于 2022/01/24。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

