lowdb vs nedb vs levelup vs mongodb-memory-server vs pouchdb vs sqlite3
Node.js Database Libraries
lowdbnedblevelupmongodb-memory-serverpouchdbsqlite3Similar Packages:

Node.js Database Libraries

Node.js Database Libraries are tools that allow Node.js applications to interact with various types of databases, including relational, NoSQL, and in-memory databases. These libraries provide APIs for performing CRUD (Create, Read, Update, Delete) operations, managing connections, and executing queries. They abstract the complexities of database interactions, making it easier for developers to integrate data storage and retrieval functionalities into their applications. Examples include mongoose for MongoDB, sequelize for SQL databases, and knex for query building.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
lowdb1,984,51022,47222.9 kB152 years agoMIT
nedb118,10313,565-20910 years agoSEE LICENSE IN LICENSE
levelup04,079-04 years agoMIT
mongodb-memory-server02,8074.54 kB152 months agoMIT
pouchdb017,5475.53 MB1642 years agoApache-2.0
sqlite306,4243.35 MB1742 years agoBSD-3-Clause

Feature Comparison: lowdb vs nedb vs levelup vs mongodb-memory-server vs pouchdb vs sqlite3

Database Type

  • lowdb:

    lowdb is a small local JSON database powered by Lodash. It is a simple and lightweight solution for storing data in JSON format, making it ideal for small projects, prototypes, or applications that need a quick and easy way to manage data without the complexity of a full database system.

  • nedb:

    nedb is a lightweight, embedded NoSQL database for Node.js applications. It stores data in JSON format and provides a simple API for CRUD operations, making it easy to integrate into projects that require a fast and efficient way to manage data without the overhead of a full database server.

  • levelup:

    levelup is a Node.js library that provides a simple, high-level API for interacting with LevelDB and other key-value stores. It is designed for applications that require fast, low-latency access to data stored as key-value pairs.

  • mongodb-memory-server:

    mongodb-memory-server is a Node.js package that allows you to spin up a MongoDB server in memory for testing purposes. It is particularly useful for automated tests, as it eliminates the need for a separate MongoDB instance and allows for quick setup and teardown of the database.

  • pouchdb:

    pouchdb is an open-source JavaScript database that syncs with CouchDB and other compatible servers. It is designed for web and mobile applications, providing offline storage and synchronization capabilities, making it ideal for apps that need to work seamlessly without an internet connection.

  • sqlite3:

    sqlite3 is a Node.js driver for SQLite, a self-contained, serverless, and lightweight relational database. It provides a simple API for executing SQL queries and managing database files, making it a popular choice for small to medium-sized applications that require a reliable and easy-to-use database solution.

Use Case

  • lowdb:

    lowdb is perfect for small projects, prototypes, or applications that need a simple, file-based database without the complexity of a full database system.

  • nedb:

    nedb is suitable for small to medium-sized applications that need a simple, embedded database for quick data access, such as desktop applications, small web apps, and IoT devices.

  • levelup:

    levelup is ideal for applications that require fast, low-latency access to key-value data, such as caching, real-time analytics, and lightweight data storage solutions.

  • mongodb-memory-server:

    mongodb-memory-server is designed for testing environments where you need a temporary MongoDB instance for running automated tests without the overhead of managing a real database server.

  • pouchdb:

    pouchdb is ideal for web and mobile applications that require offline data storage and synchronization with a remote database, providing a seamless experience for users with intermittent internet connectivity.

  • sqlite3:

    sqlite3 is a great choice for applications that need a lightweight relational database with full SQL support, such as mobile apps, desktop applications, and small web applications.

Data Storage

  • lowdb:

    lowdb stores data in JSON format within a single file, allowing for easy read and write operations using a simple API.

  • nedb:

    nedb stores data in JSON format, either in memory or on disk, depending on the configuration, allowing for fast access and simple data management.

  • levelup:

    levelup stores data as key-value pairs in LevelDB or other compatible backends, providing fast read and write operations with low latency.

  • mongodb-memory-server:

    mongodb-memory-server stores data in a MongoDB-compatible format, allowing you to perform standard MongoDB operations in an in-memory environment.

  • pouchdb:

    pouchdb stores data in a JSON format, supporting both local storage and synchronization with remote CouchDB-compatible databases.

  • sqlite3:

    sqlite3 stores data in a structured format using tables, rows, and columns, allowing for complex queries and data relationships.

Code Example

  • lowdb:

    lowdb Example

    const { Low, JSONFile } = require('lowdb');
    
    const db = new Low(new JSONFile('db.json'));
    
    db.read();
    
    db.data ||= { posts: [] };
    
    db.data.posts.push({ id: 1, title: 'Lowdb is awesome' });
    
    db.write();
    
    console.log(db.data);
    
  • nedb:

    nedb Example

    const Datastore = require('nedb');
    const db = new Datastore({ filename: 'data.db', autoload: true });
    
    db.insert({ name: 'Alice' }, (err, newDoc) => {
      if (err) console.error(err);
      console.log('Inserted:', newDoc);
    });
    
    db.find({ name: 'Alice' }, (err, docs) => {
      if (err) console.error(err);
      console.log('Found:', docs);
    });
    
  • levelup:

    levelup Example

    const levelup = require('levelup');
    const leveldown = require('leveldown');
    
    const db = levelup(leveldown('./mydb'));
    
    db.put('key1', 'value1', (err) => {
      if (err) return console.error('Error writing to database:', err);
      db.get('key1', (err, value) => {
        if (err) return console.error('Error reading from database:', err);
        console.log('Retrieved value:', value);
      });
    });
    
  • mongodb-memory-server:

    mongodb-memory-server Example

    const { MongoMemoryServer } = require('mongodb-memory-server');
    const mongoose = require('mongoose');
    
    const startServer = async () => {
      const mongoServer = await MongoMemoryServer.create();
      await mongoose.connect(mongoServer.getUri());
      console.log('Connected to in-memory MongoDB');
    };
    
    startServer();
    
  • pouchdb:

    pouchdb Example

    const PouchDB = require('pouchdb');
    const db = new PouchDB('mydb');
    
    db.put({ _id: 'doc1', title: 'Hello, PouchDB!' }).then(() => {
      return db.get('doc1');
    }).then((doc) => {
      console.log('Retrieved document:', doc);
    }).catch((err) => {
      console.error('Error:', err);
    });
    
  • sqlite3:

    sqlite3 Example

    const sqlite3 = require('sqlite3').verbose();
    const db = new sqlite3.Database(':memory:');
    
    db.serialize(() => {
      db.run('CREATE TABLE user (id INT, name TEXT)');
      const stmt = db.prepare('INSERT INTO user VALUES (?, ?)');
      stmt.run(1, 'Alice');
      stmt.finalize();
    
      db.each('SELECT * FROM user', (err, row) => {
        console.log(row);
      });
    });
    
    db.close();
    

How to Choose: lowdb vs nedb vs levelup vs mongodb-memory-server vs pouchdb vs sqlite3

  • lowdb:

    Choose lowdb if you need a lightweight, file-based JSON database for small projects or prototyping. It is easy to set up and use, making it ideal for applications that do not require a full-fledged database system.

  • nedb:

    Choose nedb if you need a simple, embedded NoSQL database for Node.js applications. It is lightweight, fast, and stores data in JSON format, making it suitable for small to medium-sized applications that require quick data access without the overhead of a full database server.

  • levelup:

    Choose levelup if you need a simple, high-level API for interacting with LevelDB or other key-value stores. It is suitable for applications that require fast, low-latency data access with a focus on simplicity and performance.

  • mongodb-memory-server:

    Choose mongodb-memory-server if you need a lightweight, in-memory MongoDB instance for testing purposes. It is perfect for automated tests and CI/CD pipelines, allowing you to run tests without needing a real MongoDB server.

  • pouchdb:

    Choose pouchdb if you need a client-side database that syncs with CouchDB and other compatible servers. It is ideal for applications that require offline capabilities and data synchronization across devices.

  • sqlite3:

    Choose sqlite3 if you need a self-contained, serverless SQL database that is easy to set up and use. It is suitable for small to medium-sized applications, mobile apps, and projects that require a lightweight relational database with full SQL support.

README for lowdb

lowdb Node.js CI

Simple to use type-safe local JSON database 🦉

Read or create db.json

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

Update data using Array.prototype.* and automatically write to db.json

const post = { id: 1, title: 'lowdb is awesome', views: 100 }
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.prototype.*

const { posts } = db.data
const first = posts.at(0)
const results = posts.filter((post) => post.title.includes('lowdb'))
const post1 = posts.find((post) => post.id === 1)
const sortedPosts = posts.toSorted((a, b) => a.views - b.views)

It's that simple.

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'
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'
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.