@commonify/lowdb

中文文档
3.0.0发布于 2022/01/24MITTypeScriptCommonJS近 30 天下载 4217

CommonJS version of lowdb 3.0.0. See https://github.com/mifi/commonify

原始使用文档
文档目录16 节
  1. Sponsors
  2. Features
  3. Install
  4. Usage
  5. TypeScript
  6. Lodash
  7. More examples
  8. API
  9. Classes
  10. Methods
  11. Properties
  12. Adapters
  13. Lowdb adapters
  14. Third-party adapters
  15. Writing your own adapter
  16. Limits

lowdb Node.js CI

Tiny local JSON database for small projects 🦉

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

// Save to file
db.write()
// db.json
{
  "posts": [
    { "id": 1, "title": "lowdb is awesome" }
  ]
}

If you like lowdb, see also xv (test runner) and steno (fast file writer).

Sponsors





Become a sponsor and have your company logo here.

Please help me build OSS 👉 GitHub Sponsors

Features

  • Lightweight
  • Minimalist and easy to learn API
  • Query and modify data using plain JS
  • Improved TypeScript support
  • Atomic write
  • Hackable:
    • Change storage, file format (JSON, YAML, ...) or add encryption via adapters
    • Add lodash, ramda, ... for super powers!

Install

npm install lowdb

Usage

Lowdb 2 is a pure ESM package. If you're having trouble importing it in your project, please read this.

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()
// db.json
{
  "posts": [ "hello world" ]
}

TypeScript

Lowdb now comes with TypeScript support. You can even type db.data content.

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

You can easily add lodash or other utility libraries to improve lowdb.

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

More examples

For CLI, server and browser usage, see examples/ directory.

API

Classes

Lowdb has two classes (for asynchronous and synchronous adapters).

new Low(adapter)

import { Low, JSONFile } from 'lowdb'

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

new LowSync(adapterSync)

import { LowSync, JSONFileSync } from 'lowdb'

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

Methods

db.read()

Calls adapter.read() and sets db.data.

Note: JSONFile and JSONFileSync adapters will set db.data to null if file doesn't exist.

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

db.write()

Calls adapter.write(db.data).

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

Properties

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:

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

Adapters

Lowdb adapters

JSONFile JSONFileSync

Adapters for reading and writing JSON files.

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

Memory MemorySync

In-memory adapters. Useful for speeding up unit tests.

new Low(new Memory())
new LowSync(new MemorySync())

LocalStorage

Synchronous adapter for window.localStorage.

new LowSync(new LocalStorage(name))

TextFile TextFileSync

Adapters for reading and writing text. Useful for creating custom adapters.

Third-party adapters

If you've published an adapter for lowdb, feel free to create a PR to add it here.

Writing your own adapter

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:

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

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

For example, let's say you have some async storage and want to create an adapter for it:

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)

See src/adapters/ for more examples.

Custom serialization

To create an adapter for another format than JSON, you can use TextFile or TextFileSync.

For example:

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)

Limits

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 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, MongoDB, ...

版本与发布记录

@commonify/lowdb 共发布 1 个版本,首次发布于 2022/01/24;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.0.0latest2022/01/244 年前

关于 @commonify/lowdb 的常见问题

@commonify/lowdb 是什么?

CommonJS version of lowdb 3.0.0. See https://github.com/mifi/commonify

如何安装 @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 和提交记录判断。