lowdb Local JSON Database

7.0.1 · active · verified Tue Apr 21

lowdb is a lightweight, type-safe, local JSON database designed for Node.js, Electron, and browser environments. The current stable version is 7.0.1, with a frequent release cadence that has seen multiple major and minor versions released recently, indicating active development and continuous improvement. Key differentiators include its minimalist API for interacting with data using native JavaScript array methods, robust TypeScript support for data schema, and a highly extensible architecture via 'adapters'. These adapters allow for custom storage solutions (e.g., YAML, JSON5, encryption) and seamless integration across different environments (file system for Node, localStorage or sessionStorage for browsers). It is primarily an ESM-first package, simplifying usage in modern JavaScript projects but requiring specific import patterns. It also offers convenient presets for common use cases like JSON files and browser storage, alongside automatic in-memory mode for testing.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing a type-safe lowdb instance with a JSON file in Node.js (ESM), adding data using `db.update`, querying data, and explicitly saving modifications made to `db.data`.

import { JSONFilePreset } from 'lowdb/node';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

// Resolve __dirname equivalent in ESM
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const dbFilePath = join(__dirname, 'db.json');

type Post = { id: number; title: string; views: number };
type Data = { posts: Post[] };

async function runDbExample() {
  // Define default data with type safety
  const defaultData: Data = { posts: [] };

  // Initialize the database with a JSON file adapter
  // This will create 'db.json' if it doesn't exist, populated with defaultData
  const db = await JSONFilePreset<Data>(dbFilePath, defaultData);

  // Read the current data from the file
  await db.read();
  console.log('Initial data:', db.data);

  // Add a new post using db.update() for atomic writes and automatic saving
  const newPost = { id: 1, title: 'lowdb is awesome', views: 100 };
  await db.update(({ posts }) => posts.push(newPost));
  console.log('Data after adding post:', db.data);

  // Query data using native JavaScript array methods
  const { posts } = db.data;
  const firstPost = posts.at(0);
  console.log('First post:', firstPost);

  // Modify an existing item and explicitly save
  if (firstPost) {
    firstPost.views += 10; // Modify in memory
    console.log('Modified post in memory:', firstPost);
    await db.write(); // Explicitly write changes back to db.json
  }
  console.log('Final data after explicit write:', db.data);
}

runDbExample().catch(console.error);

view raw JSON →