Repository: typicode/lowdb
Branch: main
Commit: 966a3fde68b8
Files: 37
Total size: 29.4 KB
Directory structure:
gitextract_re_ccba0/
├── .commitlintrc.json
├── .eslintrc.json
├── .gitattributes
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ └── node.js.yml
├── .gitignore
├── .husky/
│ ├── .gitignore
│ ├── commit-msg
│ └── pre-commit
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── package.json
├── src/
│ ├── adapters/
│ │ ├── Memory.test.ts
│ │ ├── Memory.ts
│ │ ├── browser/
│ │ │ ├── LocalStorage.ts
│ │ │ ├── SessionStorage.ts
│ │ │ ├── WebStorage.test.ts
│ │ │ └── WebStorage.ts
│ │ └── node/
│ │ ├── DataFile.ts
│ │ ├── JSONFile.test.ts
│ │ ├── JSONFile.ts
│ │ ├── TextFile.test.ts
│ │ └── TextFile.ts
│ ├── browser.ts
│ ├── core/
│ │ ├── Low.test.ts
│ │ └── Low.ts
│ ├── examples/
│ │ ├── README.md
│ │ ├── browser.ts
│ │ ├── cli.ts
│ │ ├── in-memory.ts
│ │ └── server.ts
│ ├── index.ts
│ ├── node.ts
│ └── presets/
│ ├── browser.ts
│ └── node.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .commitlintrc.json
================================================
{ "extends": ["@commitlint/config-conventional"] }
================================================
FILE: .eslintrc.json
================================================
{
"extends": "@typicode",
"env":{
"browser": true,
"node": true
}
}
================================================
FILE: .gitattributes
================================================
*.ts linguist-language=JavaScript
================================================
FILE: .github/FUNDING.yml
================================================
github: typicode
================================================
FILE: .github/workflows/node.js.yml
================================================
name: Node.js CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x, 20.x]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run build --if-present
- run: npm test
================================================
FILE: .gitignore
================================================
lib
node_modules
================================================
FILE: .husky/.gitignore
================================================
_
================================================
FILE: .husky/commit-msg
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit "$1"
================================================
FILE: .husky/pre-commit
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint
npm test
================================================
FILE: CONTRIBUTING.md
================================================
By contributing, you agree to release your modifications under the MIT
license (see the file LICENSE-MIT).
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2021 typicode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# lowdb [](https://www.npmjs.org/package/lowdb) [](https://github.com/typicode/lowdb/actions/workflows/node.js.yml)
> Simple to use type-safe local JSON database 🦉
>
> If you know JavaScript, you know how to use lowdb.
Read or create `db.json`
```js
const db = await JSONFilePreset('db.json', { posts: [] })
```
Use plain JavaScript to change data
```js
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))
```
```js
// db.json
{
"posts": [
{ "id": 1, "title": "lowdb is awesome", "views": 100 }
]
}
```
In the same spirit, query using native `Array` functions:
```js
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](https://github.com/sponsors/typicode) 👉 [GitHub Sponsors](https://github.com/sponsors/typicode)
## Features
- **Lightweight**
- **Minimalist**
- **TypeScript**
- **Plain JavaScript**
- Safe atomic writes
- Hackable:
- Change storage, file format (JSON, YAML, ...) or add encryption via [adapters](#adapters)
- Extend it with lodash, ramda, ... for super powers!
- Automatically switches to fast in-memory mode during tests
## Install
```sh
npm install lowdb
```
## Usage
_Lowdb is a pure ESM package. If you're having trouble using it in your project, please [read this](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c)._
```js
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()
```
```js
// db.json
{
"posts": [ "hello world" ]
}
```
### TypeScript
You can use TypeScript to check your data types.
```ts
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.
```ts
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')
const db = new LowWithLodash(adapter, defaultData)
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/`](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/`](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)`
```js
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)`
```js
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.
```js
db.data // === null
db.read()
db.data // !== null
```
#### `db.write()`
Calls `adapter.write(db.data)`.
```js
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()`.
```js
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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).
For example:
```js
db.data = 'string'
db.data = [1, 2, 3]
db.data = { key: 'value' }
```
## Adapters
### Lowdb adapters
#### `JSONFile` `JSONFileSync`
Adapters for reading and writing JSON files.
```js
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/`](src/examples) directory.
```js
import { Memory, MemorySync } from 'lowdb'
new Low(new Memory(), {})
new LowSync(new MemorySync(), {})
```
#### `LocalStorage` `SessionStorage`
Synchronous adapter for `window.localStorage` and `window.sessionStorage`.
```js
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...).
```js
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:
```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
}
```
For example, let's say you have some async storage and want to create an adapter for it:
```js
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/`](src/adapters) for more examples.
#### Custom serialization
To create an adapter for another format than JSON, you can use `TextFile` or `TextFileSync`.
For example:
```js
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.
================================================
FILE: package.json
================================================
{
"name": "lowdb",
"version": "7.0.1",
"description": "Tiny local JSON database for Node, Electron and the browser",
"keywords": [
"database",
"db",
"electron",
"embed",
"embedded",
"flat",
"JSON",
"local",
"localStorage",
"sessionStorage",
"browser",
"esm"
],
"homepage": "https://github.com/typicode/lowdb#readme",
"bugs": {
"url": "https://github.com/typicode/lowdb/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/typicode/lowdb.git"
},
"funding": "https://github.com/sponsors/typicode",
"license": "MIT",
"author": "Typicode <typicode@gmail.com>",
"type": "module",
"exports": {
".": "./lib/index.js",
"./node": "./lib/node.js",
"./browser": "./lib/browser.js"
},
"types": "./lib",
"typesVersions": {
"*": {
"node": [
"lib/node.d.ts"
],
"browser": [
"lib/browser.d.ts"
]
}
},
"files": [
"lib",
"!lib/examples/**/*",
"!lib/**/*.test.*"
],
"scripts": {
"test": "node --import tsx/esm --test src/**/*.test.ts src/**/**/*.test.ts",
"lint": "eslint src --ext .ts --ignore-path .gitignore",
"build": "del-cli lib && tsc",
"prepublishOnly": "npm run build",
"postversion": "git push --follow-tags && npm publish",
"prepare": "husky install"
},
"dependencies": {
"steno": "^4.0.2"
},
"devDependencies": {
"@commitlint/cli": "^18.4.3",
"@commitlint/config-conventional": "^18.4.3",
"@commitlint/prompt-cli": "^18.4.3",
"@sindresorhus/tsconfig": "^5.0.0",
"@types/express": "^4.17.21",
"@types/lodash": "^4.14.202",
"@types/node": "^20.10.5",
"@typicode/eslint-config": "^1.2.0",
"del-cli": "^5.1.0",
"eslint": "^8.56.0",
"express-async-handler": "^1.2.0",
"husky": "^8.0.3",
"lodash": "^4.17.21",
"tempy": "^3.1.0",
"ts-node": "^10.9.2",
"tsx": "^4.7.0",
"typescript": "^5.3.3"
},
"engines": {
"node": ">=18"
}
}
================================================
FILE: src/adapters/Memory.test.ts
================================================
import { deepEqual, equal } from 'node:assert/strict'
import test from 'node:test'
import { Memory, MemorySync } from './Memory.js'
await test('Memory', async () => {
const obj = { a: 1 }
const memory = new Memory()
// Null by default
equal(await memory.read(), null)
// Write
equal(await memory.write(obj), undefined)
// Read
deepEqual(await memory.read(), obj)
})
await test('MemorySync', () => {
const obj = { a: 1 }
const memory = new MemorySync()
// Null by default
equal(memory.read(), null)
// Write
equal(memory.write(obj), undefined)
// Read
deepEqual(memory.read(), obj)
})
================================================
FILE: src/adapters/Memory.ts
================================================
import { Adapter, SyncAdapter } from '../core/Low.js'
export class Memory<T> implements Adapter<T> {
#data: T | null = null
read(): Promise<T | null> {
return Promise.resolve(this.#data)
}
write(obj: T): Promise<void> {
this.#data = obj
return Promise.resolve()
}
}
export class MemorySync<T> implements SyncAdapter<T> {
#data: T | null = null
read(): T | null {
return this.#data || null
}
write(obj: T): void {
this.#data = obj
}
}
================================================
FILE: src/adapters/browser/LocalStorage.ts
================================================
import { WebStorage } from './WebStorage.js'
export class LocalStorage<T> extends WebStorage<T> {
constructor(key: string) {
super(key, localStorage)
}
}
================================================
FILE: src/adapters/browser/SessionStorage.ts
================================================
import { WebStorage } from './WebStorage.js'
export class SessionStorage<T> extends WebStorage<T> {
constructor(key: string) {
super(key, sessionStorage)
}
}
================================================
FILE: src/adapters/browser/WebStorage.test.ts
================================================
import { deepEqual, equal } from 'node:assert/strict'
import test from 'node:test'
import { WebStorage } from './WebStorage.js'
const storage: { [key: string]: string } = {}
// Mock localStorage
const mockStorage = () => ({
getItem: (key: string): string | null => storage[key] || null,
setItem: (key: string, data: string) => (storage[key] = data),
length: 1,
removeItem() {
return
},
clear() {
return
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
key(_: number): string {
return ''
},
})
global.localStorage = mockStorage()
global.sessionStorage = mockStorage()
await test('localStorage', () => {
const obj = { a: 1 }
const storage = new WebStorage('key', localStorage)
// Write
equal(storage.write(obj), undefined)
// Read
deepEqual(storage.read(), obj)
})
await test('sessionStorage', () => {
const obj = { a: 1 }
const storage = new WebStorage('key', sessionStorage)
// Write
equal(storage.write(obj), undefined)
// Read
deepEqual(storage.read(), obj)
})
================================================
FILE: src/adapters/browser/WebStorage.ts
================================================
import { SyncAdapter } from '../../core/Low.js'
export class WebStorage<T> implements SyncAdapter<T> {
#key: string
#storage: Storage
constructor(key: string, storage: Storage) {
this.#key = key
this.#storage = storage
}
read(): T | null {
const value = this.#storage.getItem(this.#key)
if (value === null) {
return null
}
return JSON.parse(value) as T
}
write(obj: T): void {
this.#storage.setItem(this.#key, JSON.stringify(obj))
}
}
================================================
FILE: src/adapters/node/DataFile.ts
================================================
import { PathLike } from 'fs'
import { Adapter, SyncAdapter } from '../../core/Low.js'
import { TextFile, TextFileSync } from './TextFile.js'
export class DataFile<T> implements Adapter<T> {
#adapter: TextFile
#parse: (str: string) => T
#stringify: (data: T) => string
constructor(
filename: PathLike,
{
parse,
stringify,
}: {
parse: (str: string) => T
stringify: (data: T) => string
},
) {
this.#adapter = new TextFile(filename)
this.#parse = parse
this.#stringify = stringify
}
async read(): Promise<T | null> {
const data = await this.#adapter.read()
if (data === null) {
return null
} else {
return this.#parse(data)
}
}
write(obj: T): Promise<void> {
return this.#adapter.write(this.#stringify(obj))
}
}
export class DataFileSync<T> implements SyncAdapter<T> {
#adapter: TextFileSync
#parse: (str: string) => T
#stringify: (data: T) => string
constructor(
filename: PathLike,
{
parse,
stringify,
}: {
parse: (str: string) => T
stringify: (data: T) => string
},
) {
this.#adapter = new TextFileSync(filename)
this.#parse = parse
this.#stringify = stringify
}
read(): T | null {
const data = this.#adapter.read()
if (data === null) {
return null
} else {
return this.#parse(data)
}
}
write(obj: T): void {
this.#adapter.write(this.#stringify(obj))
}
}
================================================
FILE: src/adapters/node/JSONFile.test.ts
================================================
import { deepEqual, equal } from 'node:assert/strict'
import test from 'node:test'
import { temporaryFile } from 'tempy'
import { JSONFile, JSONFileSync } from './JSONFile.js'
type Data = {
a: number
}
await test('JSONFile', async () => {
const obj = { a: 1 }
const file = new JSONFile<Data>(temporaryFile())
// Null if file doesn't exist
equal(await file.read(), null)
// Write
equal(await file.write(obj), undefined)
// Read
deepEqual(await file.read(), obj)
})
await test('JSONFileSync', () => {
const obj = { a: 1 }
const file = new JSONFileSync<Data>(temporaryFile())
// Null if file doesn't exist
equal(file.read(), null)
// Write
equal(file.write(obj), undefined)
// Read
deepEqual(file.read(), obj)
})
================================================
FILE: src/adapters/node/JSONFile.ts
================================================
import { PathLike } from 'fs'
import { DataFile, DataFileSync } from './DataFile.js'
export class JSONFile<T> extends DataFile<T> {
constructor(filename: PathLike) {
super(filename, {
parse: JSON.parse,
stringify: (data: T) => JSON.stringify(data, null, 2),
})
}
}
export class JSONFileSync<T> extends DataFileSync<T> {
constructor(filename: PathLike) {
super(filename, {
parse: JSON.parse,
stringify: (data: T) => JSON.stringify(data, null, 2),
})
}
}
================================================
FILE: src/adapters/node/TextFile.test.ts
================================================
import { deepEqual, equal } from 'node:assert/strict'
import test from 'node:test'
import { temporaryFile } from 'tempy'
import { TextFile, TextFileSync } from './TextFile.js'
await test('TextFile', async () => {
const str = 'foo'
const file = new TextFile(temporaryFile())
// Null if file doesn't exist
equal(await file.read(), null)
// Write
equal(await file.write(str), undefined)
// Read
deepEqual(await file.read(), str)
})
await test('TextFileSync', () => {
const str = 'foo'
const file = new TextFileSync(temporaryFile())
// Null if file doesn't exist
equal(file.read(), null)
// Write
equal(file.write(str), undefined)
// Read
deepEqual(file.read(), str)
})
await test('RaceCondition', async () => {
const file = new TextFile(temporaryFile())
const promises: Promise<void>[] = []
let i = 0
for (; i <= 100; i++) {
promises.push(file.write(String(i)))
}
await Promise.all(promises)
equal(await file.read(), String(i - 1))
})
================================================
FILE: src/adapters/node/TextFile.ts
================================================
import { PathLike, readFileSync, renameSync, writeFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { Writer } from 'steno'
import { Adapter, SyncAdapter } from '../../core/Low.js'
export class TextFile implements Adapter<string> {
#filename: PathLike
#writer: Writer
constructor(filename: PathLike) {
this.#filename = filename
this.#writer = new Writer(filename)
}
async read(): Promise<string | null> {
let data
try {
data = await readFile(this.#filename, 'utf-8')
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ENOENT') {
return null
}
throw e
}
return data
}
write(str: string): Promise<void> {
return this.#writer.write(str)
}
}
export class TextFileSync implements SyncAdapter<string> {
#tempFilename: PathLike
#filename: PathLike
constructor(filename: PathLike) {
this.#filename = filename
const f = filename.toString()
this.#tempFilename = path.join(path.dirname(f), `.${path.basename(f)}.tmp`)
}
read(): string | null {
let data
try {
data = readFileSync(this.#filename, 'utf-8')
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ENOENT') {
return null
}
throw e
}
return data
}
write(str: string): void {
writeFileSync(this.#tempFilename, str)
renameSync(this.#tempFilename, this.#filename)
}
}
================================================
FILE: src/browser.ts
================================================
export * from './adapters/browser/LocalStorage.js'
export * from './adapters/browser/SessionStorage.js'
export * from './presets/browser.js'
================================================
FILE: src/core/Low.test.ts
================================================
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { deepEqual, equal, throws } from 'node:assert/strict'
import fs from 'node:fs'
import test from 'node:test'
import lodash from 'lodash'
import { temporaryFile } from 'tempy'
import { Memory } from '../adapters/Memory.js'
import { JSONFile, JSONFileSync } from '../adapters/node/JSONFile.js'
import { Low, LowSync } from './Low.js'
type Data = {
a?: number
b?: number
}
function createJSONFile(obj: unknown): string {
const file = temporaryFile()
fs.writeFileSync(file, JSON.stringify(obj))
return file
}
function readJSONFile(file: string): unknown {
return JSON.parse(fs.readFileSync(file).toString())
}
await test('CheckArgs', () => {
const adapter = new Memory()
// Ignoring TypeScript error and pass incorrect argument
// @ts-ignore
throws(() => new Low())
// @ts-ignore
throws(() => new LowSync())
// @ts-ignore
throws(() => new Low(adapter))
// @ts-ignore
throws(() => new LowSync(adapter))
})
await test('Low', async () => {
// Create JSON file
const obj = { a: 1 }
const file = createJSONFile(obj)
// Init
const defaultData: Data = {}
const adapter = new JSONFile<Data>(file)
const low = new Low(adapter, defaultData)
await low.read()
// Data should equal file content
deepEqual(low.data, obj)
// Write new data
const newObj = { b: 2 }
low.data = newObj
await low.write()
// File content should equal new data
deepEqual(readJSONFile(file), newObj)
// Write using update()
await low.update((data) => {
data.b = 3
})
deepEqual(readJSONFile(file), { b: 3 })
})
await test('LowSync', () => {
// Create JSON file
const obj = { a: 1 }
const file = createJSONFile(obj)
// Init
const defaultData: Data = {}
const adapter = new JSONFileSync<Data>(file)
const low = new LowSync(adapter, defaultData)
low.read()
// Data should equal file content
deepEqual(low.data, obj)
// Write new data
const newObj = { b: 2 }
low.data = newObj
low.write()
// File content should equal new data
deepEqual(readJSONFile(file), newObj)
// Write using update()
low.update((data) => {
data.b = 3
})
deepEqual(readJSONFile(file), { b: 3 })
})
await test('Lodash', async () => {
// Extend with lodash
class LowWithLodash<T> extends Low<T> {
chain: lodash.ExpChain<this['data']> = lodash.chain(this).get('data')
}
// Create JSON file
const obj = { todos: ['foo', 'bar'] }
const file = createJSONFile(obj)
// Init
const defaultData = { todos: [] }
const adapter = new JSONFile<typeof obj>(file)
const low = new LowWithLodash(adapter, defaultData)
await low.read()
// Use lodash
const firstTodo = low.chain.get('todos').first().value()
equal(firstTodo, 'foo')
})
================================================
FILE: src/core/Low.ts
================================================
export interface Adapter<T> {
read: () => Promise<T | null>
write: (data: T) => Promise<void>
}
export interface SyncAdapter<T> {
read: () => T | null
write: (data: T) => void
}
function checkArgs(adapter: unknown, defaultData: unknown) {
if (adapter === undefined) throw new Error('lowdb: missing adapter')
if (defaultData === undefined) throw new Error('lowdb: missing default data')
}
export class Low<T = unknown> {
adapter: Adapter<T>
data: T
constructor(adapter: Adapter<T>, defaultData: T) {
checkArgs(adapter, defaultData)
this.adapter = adapter
this.data = defaultData
}
async read(): Promise<void> {
const data = await this.adapter.read()
if (data) this.data = data
}
async write(): Promise<void> {
if (this.data) await this.adapter.write(this.data)
}
async update(fn: (data: T) => unknown): Promise<void> {
fn(this.data)
await this.write()
}
}
export class LowSync<T = unknown> {
adapter: SyncAdapter<T>
data: T
constructor(adapter: SyncAdapter<T>, defaultData: T) {
checkArgs(adapter, defaultData)
this.adapter = adapter
this.data = defaultData
}
read(): void {
const data = this.adapter.read()
if (data) this.data = data
}
write(): void {
if (this.data) this.adapter.write(this.data)
}
update(fn: (data: T) => unknown): void {
fn(this.data)
this.write()
}
}
================================================
FILE: src/examples/README.md
================================================
# Examples
- [cli.ts](./cli.ts) - Simple CLI using JSONFileSync adapter
- [server.ts](./server.ts) - Express example using JSONFile adapter
- [browser.ts](./browser.ts) - LocalStorage adapter example
- [in-memory.ts](./in-memory.ts) - Example showing how to use in-memory adapter to write fast tests
================================================
FILE: src/examples/browser.ts
================================================
import { LocalStoragePreset } from '../presets/browser.js'
type Data = {
messages: string[]
}
const defaultData: Data = { messages: [] }
const db = LocalStoragePreset<Data>('db', defaultData)
db.update(({ messages }) => messages.push('foo'))
================================================
FILE: src/examples/cli.ts
================================================
import { JSONFileSyncPreset } from '../presets/node.js'
type Data = {
messages: string[]
}
const message = process.argv[2] || ''
const defaultData: Data = { messages: [] }
const db = JSONFileSyncPreset<Data>('file.json', defaultData)
db.update(({ messages }) => messages.push(message))
================================================
FILE: src/examples/in-memory.ts
================================================
// With this adapter, calling `db.write()` will do nothing.
// One use case for this adapter can be for tests.
import { LowSync, MemorySync, SyncAdapter } from '../index.js'
import { JSONFileSync } from '../node.js'
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace NodeJS {
interface ProcessEnv {
NODE_ENV: 'test' | 'dev' | 'prod'
}
}
}
type Data = Record<string, unknown>
const defaultData: Data = {}
const adapter: SyncAdapter<Data> =
process.env.NODE_ENV === 'test'
? new MemorySync<Data>()
: new JSONFileSync<Data>('db.json')
const db = new LowSync<Data>(adapter, defaultData)
db.read()
// Rest of your code...
================================================
FILE: src/examples/server.ts
================================================
// Note: if you're developing a local server and don't expect to get concurrent requests,
// it can be easier to use `JSONFileSync` adapter.
// But if you need to avoid blocking requests, you can do so by using `JSONFile` adapter.
import express from 'express'
import asyncHandler from 'express-async-handler'
import { JSONFilePreset } from '../presets/node.js'
const app = express()
app.use(express.json())
type Post = {
id: string
body: string
}
type Data = {
posts: Post[]
}
const defaultData: Data = { posts: [] }
const db = await JSONFilePreset<Data>('db.json', defaultData)
// db.data can be destructured to avoid typing `db.data` everywhere
const { posts } = db.data
app.get('/posts/:id', (req, res) => {
const post = posts.find((p) => p.id === req.params.id)
res.send(post)
})
app.post(
'/posts',
asyncHandler(async (req, res) => {
const post = req.body as Post
post.id = String(posts.length + 1)
await db.update(({ posts }) => posts.push(post))
res.send(post)
}),
)
app.listen(3000, () => {
console.log('listening on port 3000')
})
================================================
FILE: src/index.ts
================================================
export * from './adapters/Memory.js'
export * from './core/Low.js'
================================================
FILE: src/node.ts
================================================
export * from './adapters/node/DataFile.js'
export * from './adapters/node/JSONFile.js'
export * from './adapters/node/TextFile.js'
export * from './presets/node.js'
================================================
FILE: src/presets/browser.ts
================================================
import { LocalStorage } from '../adapters/browser/LocalStorage.js'
import { SessionStorage } from '../adapters/browser/SessionStorage.js'
import { LowSync } from '../index.js'
export function LocalStoragePreset<Data>(
key: string,
defaultData: Data,
): LowSync<Data> {
const adapter = new LocalStorage<Data>(key)
const db = new LowSync<Data>(adapter, defaultData)
db.read()
return db
}
export function SessionStoragePreset<Data>(
key: string,
defaultData: Data,
): LowSync<Data> {
const adapter = new SessionStorage<Data>(key)
const db = new LowSync<Data>(adapter, defaultData)
db.read()
return db
}
================================================
FILE: src/presets/node.ts
================================================
import { PathLike } from 'node:fs'
import { Memory, MemorySync } from '../adapters/Memory.js'
import { JSONFile, JSONFileSync } from '../adapters/node/JSONFile.js'
import { Low, LowSync } from '../core/Low.js'
export async function JSONFilePreset<Data>(
filename: PathLike,
defaultData: Data,
): Promise<Low<Data>> {
const adapter =
process.env.NODE_ENV === 'test'
? new Memory<Data>()
: new JSONFile<Data>(filename)
const db = new Low<Data>(adapter, defaultData)
await db.read()
return db
}
export function JSONFileSyncPreset<Data>(
filename: PathLike,
defaultData: Data,
): LowSync<Data> {
const adapter =
process.env.NODE_ENV === 'test'
? new MemorySync<Data>()
: new JSONFileSync<Data>(filename)
const db = new LowSync<Data>(adapter, defaultData)
db.read()
return db
}
================================================
FILE: tsconfig.json
================================================
{
"extends": "@sindresorhus/tsconfig",
"compilerOptions": {
"outDir": "./lib"
}
}
gitextract_re_ccba0/ ├── .commitlintrc.json ├── .eslintrc.json ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ └── workflows/ │ └── node.js.yml ├── .gitignore ├── .husky/ │ ├── .gitignore │ ├── commit-msg │ └── pre-commit ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── package.json ├── src/ │ ├── adapters/ │ │ ├── Memory.test.ts │ │ ├── Memory.ts │ │ ├── browser/ │ │ │ ├── LocalStorage.ts │ │ │ ├── SessionStorage.ts │ │ │ ├── WebStorage.test.ts │ │ │ └── WebStorage.ts │ │ └── node/ │ │ ├── DataFile.ts │ │ ├── JSONFile.test.ts │ │ ├── JSONFile.ts │ │ ├── TextFile.test.ts │ │ └── TextFile.ts │ ├── browser.ts │ ├── core/ │ │ ├── Low.test.ts │ │ └── Low.ts │ ├── examples/ │ │ ├── README.md │ │ ├── browser.ts │ │ ├── cli.ts │ │ ├── in-memory.ts │ │ └── server.ts │ ├── index.ts │ ├── node.ts │ └── presets/ │ ├── browser.ts │ └── node.ts └── tsconfig.json
SYMBOL INDEX (65 symbols across 17 files)
FILE: src/adapters/Memory.ts
class Memory (line 3) | class Memory<T> implements Adapter<T> {
method read (line 6) | read(): Promise<T | null> {
method write (line 10) | write(obj: T): Promise<void> {
class MemorySync (line 16) | class MemorySync<T> implements SyncAdapter<T> {
method read (line 19) | read(): T | null {
method write (line 23) | write(obj: T): void {
FILE: src/adapters/browser/LocalStorage.ts
class LocalStorage (line 3) | class LocalStorage<T> extends WebStorage<T> {
method constructor (line 4) | constructor(key: string) {
FILE: src/adapters/browser/SessionStorage.ts
class SessionStorage (line 3) | class SessionStorage<T> extends WebStorage<T> {
method constructor (line 4) | constructor(key: string) {
FILE: src/adapters/browser/WebStorage.test.ts
method removeItem (line 13) | removeItem() {
method clear (line 16) | clear() {
method key (line 20) | key(_: number): string {
FILE: src/adapters/browser/WebStorage.ts
class WebStorage (line 3) | class WebStorage<T> implements SyncAdapter<T> {
method constructor (line 7) | constructor(key: string, storage: Storage) {
method read (line 12) | read(): T | null {
method write (line 22) | write(obj: T): void {
FILE: src/adapters/node/DataFile.ts
class DataFile (line 6) | class DataFile<T> implements Adapter<T> {
method constructor (line 11) | constructor(
method read (line 26) | async read(): Promise<T | null> {
method write (line 35) | write(obj: T): Promise<void> {
class DataFileSync (line 40) | class DataFileSync<T> implements SyncAdapter<T> {
method constructor (line 45) | constructor(
method read (line 60) | read(): T | null {
method write (line 69) | write(obj: T): void {
FILE: src/adapters/node/JSONFile.test.ts
type Data (line 8) | type Data = {
FILE: src/adapters/node/JSONFile.ts
class JSONFile (line 5) | class JSONFile<T> extends DataFile<T> {
method constructor (line 6) | constructor(filename: PathLike) {
class JSONFileSync (line 14) | class JSONFileSync<T> extends DataFileSync<T> {
method constructor (line 15) | constructor(filename: PathLike) {
FILE: src/adapters/node/TextFile.ts
class TextFile (line 9) | class TextFile implements Adapter<string> {
method constructor (line 13) | constructor(filename: PathLike) {
method read (line 18) | async read(): Promise<string | null> {
method write (line 33) | write(str: string): Promise<void> {
class TextFileSync (line 38) | class TextFileSync implements SyncAdapter<string> {
method constructor (line 42) | constructor(filename: PathLike) {
method read (line 48) | read(): string | null {
method write (line 63) | write(str: string): void {
FILE: src/core/Low.test.ts
type Data (line 13) | type Data = {
function createJSONFile (line 18) | function createJSONFile(obj: unknown): string {
function readJSONFile (line 24) | function readJSONFile(file: string): unknown {
class LowWithLodash (line 101) | class LowWithLodash<T> extends Low<T> {
FILE: src/core/Low.ts
type Adapter (line 1) | interface Adapter<T> {
type SyncAdapter (line 6) | interface SyncAdapter<T> {
function checkArgs (line 11) | function checkArgs(adapter: unknown, defaultData: unknown) {
class Low (line 16) | class Low<T = unknown> {
method constructor (line 20) | constructor(adapter: Adapter<T>, defaultData: T) {
method read (line 26) | async read(): Promise<void> {
method write (line 31) | async write(): Promise<void> {
method update (line 35) | async update(fn: (data: T) => unknown): Promise<void> {
class LowSync (line 41) | class LowSync<T = unknown> {
method constructor (line 45) | constructor(adapter: SyncAdapter<T>, defaultData: T) {
method read (line 51) | read(): void {
method write (line 56) | write(): void {
method update (line 60) | update(fn: (data: T) => unknown): void {
FILE: src/examples/browser.ts
type Data (line 3) | type Data = {
FILE: src/examples/cli.ts
type Data (line 3) | type Data = {
FILE: src/examples/in-memory.ts
type ProcessEnv (line 9) | interface ProcessEnv {
type Data (line 15) | type Data = Record<string, unknown>
FILE: src/examples/server.ts
type Post (line 12) | type Post = {
type Data (line 17) | type Data = {
FILE: src/presets/browser.ts
function LocalStoragePreset (line 5) | function LocalStoragePreset<Data>(
function SessionStoragePreset (line 15) | function SessionStoragePreset<Data>(
FILE: src/presets/node.ts
function JSONFilePreset (line 7) | async function JSONFilePreset<Data>(
function JSONFileSyncPreset (line 20) | function JSONFileSyncPreset<Data>(
Condensed preview — 37 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (34K chars).
[
{
"path": ".commitlintrc.json",
"chars": 51,
"preview": "{ \"extends\": [\"@commitlint/config-conventional\"] }\n"
},
{
"path": ".eslintrc.json",
"chars": 82,
"preview": "{\n \"extends\": \"@typicode\",\n \"env\":{\n \"browser\": true,\n \"node\": true\n }\n}\n"
},
{
"path": ".gitattributes",
"chars": 34,
"preview": "*.ts linguist-language=JavaScript\n"
},
{
"path": ".github/FUNDING.yml",
"chars": 16,
"preview": "github: typicode"
},
{
"path": ".github/workflows/node.js.yml",
"chars": 477,
"preview": "name: Node.js CI\n\non:\n push:\n branches: [main]\n pull_request:\n branches: [main]\n\njobs:\n build:\n runs-on: ubu"
},
{
"path": ".gitignore",
"chars": 17,
"preview": "lib\nnode_modules\n"
},
{
"path": ".husky/.gitignore",
"chars": 2,
"preview": "_\n"
},
{
"path": ".husky/commit-msg",
"chars": 82,
"preview": "#!/bin/sh\n. \"$(dirname \"$0\")/_/husky.sh\"\n\nnpx --no-install commitlint --edit \"$1\"\n"
},
{
"path": ".husky/pre-commit",
"chars": 64,
"preview": "#!/bin/sh\n. \"$(dirname \"$0\")/_/husky.sh\"\n\nnpm run lint\nnpm test\n"
},
{
"path": "CONTRIBUTING.md",
"chars": 107,
"preview": "By contributing, you agree to release your modifications under the MIT\nlicense (see the file LICENSE-MIT).\n"
},
{
"path": "LICENSE",
"chars": 1065,
"preview": "MIT License\n\nCopyright (c) 2021 typicode\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\no"
},
{
"path": "README.md",
"chars": 9177,
"preview": "# lowdb [](https://www.npmjs.org/package/lowdb) [ => Promise<T | null>\n write: (data: T) => Promise<void>\n}\n\nexport interface Sy"
},
{
"path": "src/examples/README.md",
"chars": 301,
"preview": "# Examples\n\n- [cli.ts](./cli.ts) - Simple CLI using JSONFileSync adapter\n- [server.ts](./server.ts) - Express example us"
},
{
"path": "src/examples/browser.ts",
"chars": 247,
"preview": "import { LocalStoragePreset } from '../presets/browser.js'\n\ntype Data = {\n messages: string[]\n}\n\nconst defaultData: Dat"
},
{
"path": "src/examples/cli.ts",
"chars": 292,
"preview": "import { JSONFileSyncPreset } from '../presets/node.js'\n\ntype Data = {\n messages: string[]\n}\n\nconst message = process.a"
},
{
"path": "src/examples/in-memory.ts",
"chars": 686,
"preview": "// With this adapter, calling `db.write()` will do nothing.\n// One use case for this adapter can be for tests.\nimport { "
},
{
"path": "src/examples/server.ts",
"chars": 1084,
"preview": "// Note: if you're developing a local server and don't expect to get concurrent requests,\n// it can be easier to use `JS"
},
{
"path": "src/index.ts",
"chars": 67,
"preview": "export * from './adapters/Memory.js'\nexport * from './core/Low.js'\n"
},
{
"path": "src/node.ts",
"chars": 166,
"preview": "export * from './adapters/node/DataFile.js'\nexport * from './adapters/node/JSONFile.js'\nexport * from './adapters/node/T"
},
{
"path": "src/presets/browser.ts",
"chars": 626,
"preview": "import { LocalStorage } from '../adapters/browser/LocalStorage.js'\nimport { SessionStorage } from '../adapters/browser/S"
},
{
"path": "src/presets/node.ts",
"chars": 832,
"preview": "import { PathLike } from 'node:fs'\n\nimport { Memory, MemorySync } from '../adapters/Memory.js'\nimport { JSONFile, JSONFi"
},
{
"path": "tsconfig.json",
"chars": 92,
"preview": "{\n \"extends\": \"@sindresorhus/tsconfig\",\n \"compilerOptions\": {\n \"outDir\": \"./lib\"\n }\n}\n"
}
]
About this extraction
This page contains the full source code of the typicode/lowdb GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 37 files (29.4 KB), approximately 9.0k tokens, and a symbol index with 65 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.