JSON File Database for Node.js

2.6.0 · active · verified Wed Apr 22

node-json-db is a lightweight, file-based database for Node.js, storing data directly in a JSON file. It is currently at stable version 2.6.0 and maintains an active release cadence, with several minor and patch releases occurring monthly or bi-monthly in the past year. Its primary differentiator is the use of a "DataPath" system, akin to XMLPath, for navigating and accessing nested data structures within the JSON file. All operations are asynchronous, leveraging `async/await`. It supports configurable database names, auto-save on push, human-readable file formats, custom separators, and since v2.6.0, serialization of complex JavaScript types like `Set`, `Map`, `Date`, `RegExp`, and `BigInt` via an `ISerializer` contract. This makes it suitable for simple, local data persistence where a full-fledged database system is overkill.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing the database, pushing data (including merging objects), retrieving data, and handling errors for non-existent paths. Requires Node.js ESM support.

import { JsonDB, Config, DataError } from "node-json-db";
import * as fs from 'fs'; // For cleanup

async function runExample() {
  const dbFileName = "myQuickstartDatabase";
  const dbFilePath = `${dbFileName}.json`;

  // Clean up previous run if exists
  if (fs.existsSync(dbFilePath)) {
    fs.unlinkSync(dbFilePath);
  }

  // Initialize JsonDB with a Config object
  // Arguments: filename, autoSave (true), humanReadable (false), separator ('/'), syncWrites (false)
  const db = new JsonDB(new Config(dbFileName, true, false, "/", false));

  console.log("Database initialized.");

  // Push simple string data to a path
  await db.push("/user/name", "Alice Wonderland");
  console.log("Pushed /user/name: Alice Wonderland");

  // Push an object, creating hierarchy if needed
  await db.push("/settings", { theme: "dark", notifications: true });
  console.log("Pushed /settings: { theme: 'dark', notifications: true }");

  // Merge new data into an existing object path (third argument 'false' for merge)
  await db.push(
    "/settings",
    { notifications: false, language: "en-US" },
    false
  );
  console.log("Merged into /settings: { notifications: false, language: 'en-US' }");
  console.log("Current /settings:", await db.getData("/settings"));

  // Get data from a specific path
  const userName = await db.getData("/user/name");
  console.log("Retrieved /user/name:", userName);

  // Attempt to get data from a non-existent path and catch the expected error
  try {
    await db.getData("/nonexistent/path");
  } catch (error) {
    if (error instanceof DataError) {
      console.error(`Caught expected error for non-existent path: ${error.message}`);
    } else {
      console.error("Caught unexpected error:", error);
    }
  }

  // Get the entire database content
  const fullData = await db.getData("/");
  console.log("Full database content:\n", JSON.stringify(fullData, null, 2));

  console.log("\nQuickstart example finished.");
}

runExample().catch(console.error);

view raw JSON →