JSON File Database for Node.js

2.0.3 · active · verified Wed Apr 22

json-file-database is a lightweight, TypeScript-first file-system-based database designed for Node.js projects that don't require the overhead of a traditional database server. It stores data directly in JSON files, abstracting away the complexities of `fs` and `JSON.parse`/`JSON.stringify` operations. The current stable version is 2.0.3, which introduced breaking changes to allow for a customizable primary key beyond just 'id'. The library differentiates itself by offering pure TypeScript support for fewer type-related errors, debounced writes to minimize disk I/O, and `O(log n)` time complexity for data operations through binary search, making it efficient for small to medium-sized datasets. It's suitable for prototyping, small applications, or configuration management where a simple, local persistence layer is preferred.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a JSON file database, initialize it with data, create a typed collection, and perform basic CRUD (Create, Read, Update, Delete) operations using the library's API.

import { connect } from 'json-file-database'

/**
 * Define the shape of your data. It must include the primary key property.
 */
type User = { id: number, name: string, email: string }

/**
 * Connect to the database file. If it doesn't exist, it will be created.
 * The `init` property provides initial data if the file is new.
 */
const db = connect({
  file: './my-app-db.json',
  init: {
    users: [
      { id: 1, name: 'Alice', email: 'alice@example.com' },
      { id: 2, name: 'Bob', email: 'bob@example.com' },
    ],
    products: [
      { id: 101, name: 'Laptop', price: 1200 },
    ]
  }
})

/**
 * Get a typed collection instance, specifying the data type and primary key.
 * For v2+, the `primaryKey` option is mandatory if it's not 'id'.
 */
const users = db<User>({
  name: 'users',
  primaryKey: 'id',
})

// --- Perform CRUD operations ---

// Find by primary key
console.log('User with id 1:', users.find({ id: 1 }))

// Insert a new user
const newUser: User = { id: 3, name: 'Charlie', email: 'charlie@example.com' }
console.log('Inserting new user:', users.insert(newUser))

// List all users
console.log('All users:', Array.from(users))

// Update an existing user
console.log('Updating user 1:', users.update({ id: 1, name: 'Alicia', email: 'alicia@example.com' }))

// Remove a user
console.log('Removing user 2:', users.remove({ id: 2 }))

// Verify the changes
console.log('Users after operations:', Array.from(users))

view raw JSON →