lowdb

lowdb

简单易用的轻量级本地 JSON 数据库

lowdb 是一个轻量级本地 JSON 数据库,支持类型安全和纯 JavaScript 操作。它具有原子写入、可扩展性强、支持 TypeScript 等特点。lowdb 能够简单读写 JSON 文件,支持内存模式加速测试,并可通过适配器扩展存储方式或文件格式。这个开源项目适合小型项目和快速原型开发,为开发者提供了简洁有力的本地数据存储方案。

lowdbJSON数据库JavaScript轻量级TypeScriptGithub开源项目

lowdb Node.js CI

Simple to use type-safe local JSON database 🦉

If you know JavaScript, you know how to use lowdb.

Read or create db.json

const db = await JSONFilePreset('db.json', { posts: [] })

Use plain JavaScript to change data

const post = { id: 1, title: 'lowdb is awesome', views: 100 } // In two steps db.data.posts.push(post) await db.write() // Or in one await db.update(({ posts }) => posts.push(post))
// db.json { "posts": [ { "id": 1, "title": "lowdb is awesome", "views": 100 } ] }

In the same spirit, query using native Array functions:

const { posts } = db.data posts.at(0) // First post posts.filter((post) => post.title.includes('lowdb')) // Filter by title posts.find((post) => post.id === 1) // Find by id posts.toSorted((a, b) => a.views - b.views) // Sort by views

It's that simple. db.data is just a JavaScript object, no magic.

Sponsors

<br> <br> <p align="center"> <a href="https://mockend.com/" target="_blank"> <img src="https://jsonplaceholder.typicode.com/mockend.svg" height="70px"> </a> </p> <br> <br>

Become a sponsor and have your company logo here 👉 GitHub Sponsors

Features

  • Lightweight
  • Minimalist
  • TypeScript
  • Plain JavaScript
  • Safe atomic writes
  • Hackable:
    • Change storage, file format (JSON, YAML, ...) or add encryption via adapters
    • Extend it with lodash, ramda, ... for super powers!
  • Automatically switches to fast in-memory mode during tests

Install

npm install lowdb

Usage

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

import { JSONFilePreset } from 'lowdb/node' // Read or create db.json const defaultData = { posts: [] } const db = await JSONFilePreset('db.json', defaultData) // Update db.json await db.update(({ posts }) => posts.push('hello world')) // Alternatively you can call db.write() explicitely later // to write to db.json db.data.posts.push('hello world') await db.write()
// db.json { "posts": [ "hello world" ] }

TypeScript

You can use TypeScript to check your data types.

type Data = { messages: string[] } const defaultData: Data = { messages: [] } const db = await JSONPreset<Data>('db.json', defaultData) db.data.messages.push('foo') // ✅ Success db.data.messages.push(1) // ❌ TypeScript error

Lodash

You can extend lowdb with Lodash (or other libraries). To be able to extend it, we're not using JSONPreset here. Instead, we're using lower components.

import { Low } from 'lowdb' import { JSONFile } from 'lowdb/node' import lodash from 'lodash' type Post = { id: number title: string } type Data = { posts: Post[] } // Extend Low class with a new `chain` field class LowWithLodash<T> extends Low<T> { chain: lodash.ExpChain<this['data']> = lodash.chain(this).get('data') } const defaultData: Data = { posts: [], } const adapter = new JSONFile<Data>('db.json', defaultData) const db = new LowWithLodash(adapter) await db.read() // Instead of db.data use db.chain to access lodash API const post = db.chain.get('posts').find({ id: 1 }).value() // Important: value() must be called to execute chain

CLI, Server, Browser and in tests usage

See src/examples/ directory.

API

Presets

Lowdb provides four presets for common cases.

  • JSONFilePreset(filename, defaultData)
  • JSONFileSyncPreset(filename, defaultData)
  • LocalStoragePreset(name, defaultData)
  • SessionStoragePreset(name, defaultData)

See src/examples/ directory for usage.

Lowdb is extremely flexible, if you need to extend it or modify its behavior, use the classes and adapters below instead of the presets.

Classes

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

new Low(adapter, defaultData)

import { Low } from 'lowdb' import { JSONFile } from 'lowdb/node' const db = new Low(new JSONFile('file.json'), {}) await db.read() await db.write()

new LowSync(adapterSync, defaultData)

import { LowSync } from 'lowdb' import { JSONFileSync } from 'lowdb/node' 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 {}

db.update(fn)

Calls fn() then db.write().

db.update((data) => { // make changes to data // ... }) // files.json will be updated

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.

import { JSONFile, JSONFileSync } from 'lowdb/node' new Low(new JSONFile(filename), {}) new LowSync(new JSONFileSync(filename), {})

Memory MemorySync

In-memory adapters. Useful for speeding up unit tests. See src/examples/ directory.

import { Memory, MemorySync } from 'lowdb' new Low(new Memory(), {}) new LowSync(new MemorySync(), {})

LocalStorage SessionStorage

Synchronous adapter for window.localStorage and window.sessionStorage.

import { LocalStorage, SessionStorage } from 'lowdb/browser' new LowSync(new LocalStorage(name), {}) new LowSync(new SessionStorage(name), {})

Utility adapters

TextFile TextFileSync

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

DataFile DataFileSync

Adapters for easily supporting other data formats or adding behaviors (encrypt, compress...).

import { DataFile } from 'lowdb/node' new DataFile(filename, { parse: YAML.parse, stringify: YAML.stringify }) new DataFile(filename, { parse: (data) => { decypt(JSON.parse(data)) }, stringify: (str) => { encrypt(JSON.stringify(str)) } })

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 { Low } from 'lowdb' 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 } from 'lowdb' import { TextFile } from 'lowdb/node' 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 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.

编辑推荐精选

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

下拉加载更多