Convert Figma logo to code with AI

typicode logolowdb

Simple and fast JSON database

21,334
918
21,334
4

Top Related Projects

Socket.io server for Laravel Echo

Get a full fake REST API with zero coding in less than 30 seconds (seriously)

💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

13,473

The JavaScript Database, for Node.js, nw.js, electron and the browser

✨ Innovative and open-source visualization application that transforms various data formats, such as JSON, YAML, XML, CSV and more, into interactive graphs.

Easily read/write JSON files.

Quick Overview

Lowdb is a lightweight JSON database for Node.js, Electron, and the browser. It provides a simple way to store and retrieve data using a file-based JSON storage system, making it ideal for small projects, prototypes, or applications that don't require a full-fledged database.

Pros

  • Easy to set up and use with minimal configuration
  • Supports both synchronous and asynchronous operations
  • Can be used in Node.js, Electron, and browser environments
  • Extensible through custom adapters and lodash methods

Cons

  • Not suitable for large-scale applications or high-concurrency scenarios
  • Limited querying capabilities compared to full-featured databases
  • Lacks built-in data validation or schema enforcement
  • Performance may degrade with large datasets

Code Examples

  1. Basic usage:
import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'

// Create a JSON file adapter
const adapter = new JSONFile('db.json')
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: [] }

// Add a post
db.data.posts.push({ id: 1, title: 'lowdb is awesome' })

// Write db.data content to db.json
await db.write()
  1. Using lodash methods:
import lodash from 'lodash'
import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'

const adapter = new JSONFile('db.json')
const db = new Low(adapter, lodash.chain({}).value())

await db.read()

// Use lodash to find a post by id
const post = db.chain
  .get('posts')
  .find({ id: 1 })
  .value()

console.log(post)
  1. Custom adapter example:
import { Low } from 'lowdb'

// Create a custom adapter
class MyAdapter {
  async read() {
    // Custom read logic
  }

  async write(data) {
    // Custom write logic
  }
}

const adapter = new MyAdapter()
const db = new Low(adapter)

await db.read()
db.data ||= { users: [] }
db.data.users.push({ id: 1, name: 'John' })
await db.write()

Getting Started

To get started with Lowdb, follow these steps:

  1. Install Lowdb:
npm install lowdb
  1. Create a new JavaScript file (e.g., index.js) and add the following code:
import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'

const adapter = new JSONFile('db.json')
const db = new Low(adapter)

await db.read()
db.data ||= { users: [] }
db.data.users.push({ id: 1, name: 'Alice' })
await db.write()

console.log(db.data)
  1. Run the script:
node index.js

This will create a db.json file with the initial data and log the contents to the console.

Competitor Comparisons

Socket.io server for Laravel Echo

Pros of Laravel Echo Server

  • Specifically designed for real-time Laravel applications
  • Supports multiple broadcasting drivers (Redis, Socket.io)
  • Integrates seamlessly with Laravel's event broadcasting system

Cons of Laravel Echo Server

  • Limited to Laravel ecosystem, less versatile for other frameworks
  • Requires additional server setup and maintenance
  • May have higher resource consumption for small-scale applications

Code Comparison

Laravel Echo Server configuration:

module.exports = {
  authHost: 'http://localhost',
  authEndpoint: '/broadcasting/auth',
  clients: [],
  database: 'redis',
  databaseConfig: {
    redis: {},
    sqlite: {
      databasePath: '/database/laravel-echo-server.sqlite'
    }
  }
};

Lowdb usage:

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const adapter = new FileSync('db.json')
const db = low(adapter)

db.defaults({ posts: [], user: {} })
  .write()

Summary

Laravel Echo Server is a specialized solution for real-time Laravel applications, offering seamless integration with Laravel's event broadcasting system. It supports multiple broadcasting drivers but is limited to the Laravel ecosystem. Lowdb, on the other hand, is a lightweight JSON database that's more versatile and can be used in various JavaScript projects. Laravel Echo Server requires more setup and resources, while Lowdb is simpler to implement but lacks real-time capabilities.

Get a full fake REST API with zero coding in less than 30 seconds (seriously)

Pros of json-server

  • Full-featured REST API with routes, filtering, and pagination
  • Supports middleware and custom routes
  • Can be run as a standalone server or integrated into Express apps

Cons of json-server

  • Heavier and more complex than lowdb
  • Requires more setup and configuration
  • Not suitable for simple, lightweight database needs

Code Comparison

json-server:

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
server.use(router)
server.listen(3000, () => console.log('JSON Server is running'))

lowdb:

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('db.json')
const db = low(adapter)
db.defaults({ posts: [] }).write()

Key Differences

  • json-server provides a full REST API out of the box, while lowdb is a simple JSON database
  • json-server is better suited for mocking APIs and prototyping, while lowdb is ideal for small projects and simple data storage
  • json-server requires more setup but offers more features, whereas lowdb is more lightweight and easier to integrate into existing projects

Both libraries are maintained by the same author and serve different purposes. Choose json-server for API mocking and full-featured REST endpoints, and lowdb for simple, lightweight JSON-based storage in Node.js applications.

💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

Pros of localForage

  • Supports multiple storage backends (IndexedDB, WebSQL, localStorage)
  • Provides a simple, Promise-based API for easier asynchronous operations
  • Better performance for large datasets due to IndexedDB support

Cons of localForage

  • Larger file size and potentially more complex setup
  • May be overkill for simple storage needs
  • Less suitable for small, JSON-like data structures

Code Comparison

localForage:

localForage.setItem('key', 'value').then(function() {
  return localForage.getItem('key');
}).then(function(value) {
  console.log(value);
}).catch(function(err) {
  console.log(err);
});

lowdb:

const adapter = new JSONFile('db.json')
const db = new Low(adapter)

await db.read()
db.data ||= { posts: [] }
db.data.posts.push('New post')
await db.write()

Key Differences

  • localForage is designed for broader browser support and larger datasets
  • lowdb is more focused on JSON-like data and file-based storage
  • localForage uses Promises, while lowdb uses async/await
  • lowdb provides a more database-like interface with queries and updates
  • localForage is better suited for web applications, while lowdb is often used in Node.js environments

Both libraries have their strengths, and the choice between them depends on the specific requirements of your project, such as data size, storage type, and environment.

13,473

The JavaScript Database, for Node.js, nw.js, electron and the browser

Pros of NeDB

  • Supports indexing for faster queries
  • Offers in-memory and persistent storage options
  • More mature and feature-rich, with a larger community

Cons of NeDB

  • Larger bundle size compared to LowDB
  • Less active development and maintenance
  • More complex API and setup process

Code Comparison

NeDB:

const Datastore = require('nedb');
const db = new Datastore({ filename: 'path/to/datafile', autoload: true });

db.insert({ name: 'John', age: 30 }, (err, newDoc) => {
  // Handle insertion
});

LowDB:

const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');

const adapter = new FileSync('db.json');
const db = low(adapter);

db.defaults({ users: [] }).write();
db.get('users').push({ name: 'John', age: 30 }).write();

Summary

NeDB offers more advanced features like indexing and multiple storage options, making it suitable for more complex applications. However, it comes with a larger bundle size and a steeper learning curve. LowDB, on the other hand, provides a simpler API and lighter footprint, making it ideal for smaller projects or when simplicity is preferred. The choice between the two depends on the specific requirements of your project and the level of complexity you're willing to manage.

✨ Innovative and open-source visualization application that transforms various data formats, such as JSON, YAML, XML, CSV and more, into interactive graphs.

Pros of jsoncrack.com

  • Provides a visual representation of JSON data, making it easier to understand complex structures
  • Offers a web-based interface, accessible from any device with a browser
  • Supports importing and exporting JSON files, enhancing data portability

Cons of jsoncrack.com

  • Limited to JSON data visualization, while lowdb offers a full-fledged database solution
  • May not be suitable for large-scale data manipulation or querying
  • Requires an internet connection for the web-based version

Code Comparison

jsoncrack.com (React component usage):

import { JsonViewer } from "@textea/json-viewer";

const MyComponent = () => (
  <JsonViewer value={myJsonData} />
);

lowdb (Basic usage):

import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'

const db = new Low(new JSONFile('db.json'))
await db.read()
db.data ||= { posts: [] }
db.data.posts.push({ id: 1, title: 'lowdb is awesome' })
await db.write()

While jsoncrack.com focuses on visualizing JSON data in a user-friendly manner, lowdb provides a lightweight JSON database with CRUD operations. jsoncrack.com is ideal for quickly understanding JSON structures, while lowdb is better suited for applications requiring persistent data storage and manipulation.

Easily read/write JSON files.

Pros of node-jsonfile

  • Simpler and more lightweight, focusing solely on reading and writing JSON files
  • Provides synchronous and asynchronous methods for file operations
  • Supports spaces and EOL options for formatting JSON output

Cons of node-jsonfile

  • Lacks built-in querying or data manipulation features
  • No support for in-memory database operations
  • Doesn't provide automatic data persistence or real-time updates

Code Comparison

node-jsonfile:

const jsonfile = require('jsonfile')

jsonfile.readFile('file.json', (err, obj) => {
  if (err) console.error(err)
  console.log(obj)
})

lowdb:

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const adapter = new FileSync('db.json')
const db = low(adapter)

db.defaults({ posts: [] }).write()

Key Differences

  • node-jsonfile is focused on simple JSON file operations, while lowdb provides a more feature-rich database-like experience
  • lowdb offers querying capabilities and chainable methods for data manipulation
  • node-jsonfile requires manual handling of data structure, whereas lowdb provides a more abstracted interface
  • lowdb supports various adapters for different storage methods, while node-jsonfile is limited to file operations

Both libraries have their use cases: node-jsonfile for simple JSON file handling, and lowdb for more complex, database-like operations with JSON data.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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





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.

NPM DownloadsLast 30 Days