Registry / database / node-json-db

node-json-db

JSON →
library2.6.0jsnpmunverified

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.

npm install node-json-db
INSTALL
IMPORT
SIG · NODE-JSON-DB
N
node-json-db
databasejavascriptv2.6.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

JsonDB
import { JsonDB } from 'node-json-db'
import JsonDB from 'node-json-db'; const JsonDB = require('node-json-db');
JsonDB is a named export. Since v2.0.0, the library is ESM-first and all methods are asynchronous, requiring `await`.
Config
import { Config } from 'node-json-db'
const Config = require('node-json-db').Config;
Since v2.0.0, the Config object is mandatory for initializing JsonDB and must be instantiated with `new`.
DataError
import { DataError, DatabaseError } from 'node-json-db'
import { DataError } from 'node-json-db/lib/Errors'
Error classes are named exports from the main package since v2.4.2. Direct imports from '/lib/Errors' were a temporary workaround for v2.4.0/v2.4.1.

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);
Debug
Known issues
breakingAll `JsonDB` methods became asynchronous in v2.0.0. Direct calls without `await` will result in unresolved promises or unexpected behavior. Your code context must support `async/await`.
fix
Always use `await` with `JsonDB` methods (e.g., `await db.push(...)`, `await db.getData(...)`), or handle promises explicitly with `.then()/.catch()`. Ensure your code is within an `async` function or a top-level `await` context.
affects: >=2.0.0
breakingDatabase initialization now *requires* the `Config` object in v2.0.0. Passing arguments directly to the `JsonDB` constructor is no longer supported.
fix
Instantiate `JsonDB` with `new JsonDB(new Config('filename', autoSave, humanReadable, separator, syncWrites))`.
affects: >=2.0.0
gotchaThe `push` method will overwrite existing data at a given `DataPath` by default. Merging requires explicitly setting the third argument to `false`.
fix
To merge objects or arrays instead of overwriting, use `await db.push('/path', newData, false);`.
affects: >=2.0.0
gotchaWhen using `push` with the merge flag set to `false`, merging only applies to objects and arrays. Attempting to merge a primitive value (string, number, boolean) into an existing primitive will still result in an override.
fix
Be aware that primitives cannot be merged; they are always replaced. Plan your data structures accordingly if deep merging is critical.
affects: >=2.0.0
gotchaAttempting to retrieve data using `getData` from a `DataPath` that does not exist will throw a `DataError`.
fix
Wrap `getData` calls in `try-catch` blocks to gracefully handle missing data. Alternatively, use `db.getObjectDefault('/path', defaultValue)` (available since v2.2.0) if a default value is acceptable.
affects: >=2.0.0
gotchaIn versions `v2.4.0` and `v2.4.1`, several class exports (e.g., `DataError`, `DatabaseError`, adapters) were inadvertently broken, leading to import failures or `TypeError`s.
fix
Upgrade to `node-json-db@2.4.2` or higher to restore correct class exports and resolve import issues.
affects: 2.4.0, 2.4.1
Errors
Common errors & fixes
Error: DataPath '/your/non/existent/path' doesn't exist. Failed at /your.
You are attempting to retrieve data using `db.getData()` from a path that does not exist in the database.
fix
Check if the path exists before calling `getData()`, or wrap the call in a `try-catch` block. For convenience, use `db.getObjectDefault('/path', defaultValue)` (available since v2.2.0) to get a value or a fallback.
TypeError: JsonDB is not a constructor
Incorrect `import` or `require()` syntax, often trying to use CommonJS `require()` with this ESM-first package, or incorrect named import for `JsonDB`.
fix
Ensure your project is configured for ESM (`"type": "module"` in `package.json` or `.mjs` file extension) and use `import { JsonDB, Config } from 'node-json-db';`.
SyntaxError: await is only valid in async functions and the top level bodies of modules
You are calling `JsonDB` methods (which are `async`) outside of an `async` function or a top-level `await` context.
fix
Ensure all calls to `db.push()`, `db.getData()`, etc., are made from within an `async` function. For example, wrap your main logic in `async function main() { ... }` and call `main().catch(console.error);`.
TypeError: Class constructor Config cannot be invoked without 'new'
You are attempting to instantiate the `Config` class without using the `new` keyword, which is required for JavaScript classes.
fix
Always initialize `Config` with `new Config(...)` when passing it to `JsonDB`, for example: `new JsonDB(new Config('filename', true, false, '/'))`.
Upgrade
Version history
2.6.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
13 hits · last 30 days
node
10
Amazon
1
Resources
node-json-db — npm install node-json-db · libregistry