npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

lowdb-js

v0.0.6

Published

Tiny local JSON database for Node, Electron and the browser

Downloads

15

Readme

lowdb-js Node.js CI

This is a commonjs module for [email protected]. Has been refactored so that it can be used NOT only by ESM code.

lowdb

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-js 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-js')) // 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

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-js

Usage

lowdb-js is compatible with both ESM and CommonJS. Previously, original lowdb was a pure ESM package, but with this refactoring, we've restored support for CommonJS...

import { JSONFilePreset } from 'lowdb-js/node'
// or
// const { JSONFilePreset } = require('lowdb-js/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-js'
import { JSONFile } from 'lowdb-js/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-js'
import { JSONFile } from 'lowdb-js/node'

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

new LowSync(adapterSync, defaultData)

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

new Low(new Memory(), {})
new LowSync(new MemorySync(), {})

LocalStorage SessionStorage

Synchronous adapter for window.localStorage and window.sessionStorage.

import { LocalStorage, SessionStorage } from 'lowdb-js/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-js'
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 { 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-js'
import { TextFile } from 'lowdb-js/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.