{"id":16462,"library":"node-json-db","title":"JSON File Database for Node.js","description":"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.","status":"active","version":"2.6.0","language":"javascript","source_language":"en","source_url":"https://github.com/Belphemur/node-json-db","tags":["javascript","database","json","db","typescript"],"install":[{"cmd":"npm install node-json-db","lang":"bash","label":"npm"},{"cmd":"yarn add node-json-db","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-json-db","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"JsonDB is a named export. Since v2.0.0, the library is ESM-first and all methods are asynchronous, requiring `await`.","wrong":"import JsonDB from 'node-json-db';\nconst JsonDB = require('node-json-db');","symbol":"JsonDB","correct":"import { JsonDB } from 'node-json-db'"},{"note":"Since v2.0.0, the Config object is mandatory for initializing JsonDB and must be instantiated with `new`.","wrong":"const Config = require('node-json-db').Config;","symbol":"Config","correct":"import { Config } from 'node-json-db'"},{"note":"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.","wrong":"import { DataError } from 'node-json-db/lib/Errors'","symbol":"DataError","correct":"import { DataError, DatabaseError } from 'node-json-db'"}],"quickstart":{"code":"import { JsonDB, Config, DataError } from \"node-json-db\";\nimport * as fs from 'fs'; // For cleanup\n\nasync function runExample() {\n  const dbFileName = \"myQuickstartDatabase\";\n  const dbFilePath = `${dbFileName}.json`;\n\n  // Clean up previous run if exists\n  if (fs.existsSync(dbFilePath)) {\n    fs.unlinkSync(dbFilePath);\n  }\n\n  // Initialize JsonDB with a Config object\n  // Arguments: filename, autoSave (true), humanReadable (false), separator ('/'), syncWrites (false)\n  const db = new JsonDB(new Config(dbFileName, true, false, \"/\", false));\n\n  console.log(\"Database initialized.\");\n\n  // Push simple string data to a path\n  await db.push(\"/user/name\", \"Alice Wonderland\");\n  console.log(\"Pushed /user/name: Alice Wonderland\");\n\n  // Push an object, creating hierarchy if needed\n  await db.push(\"/settings\", { theme: \"dark\", notifications: true });\n  console.log(\"Pushed /settings: { theme: 'dark', notifications: true }\");\n\n  // Merge new data into an existing object path (third argument 'false' for merge)\n  await db.push(\n    \"/settings\",\n    { notifications: false, language: \"en-US\" },\n    false\n  );\n  console.log(\"Merged into /settings: { notifications: false, language: 'en-US' }\");\n  console.log(\"Current /settings:\", await db.getData(\"/settings\"));\n\n  // Get data from a specific path\n  const userName = await db.getData(\"/user/name\");\n  console.log(\"Retrieved /user/name:\", userName);\n\n  // Attempt to get data from a non-existent path and catch the expected error\n  try {\n    await db.getData(\"/nonexistent/path\");\n  } catch (error) {\n    if (error instanceof DataError) {\n      console.error(`Caught expected error for non-existent path: ${error.message}`);\n    } else {\n      console.error(\"Caught unexpected error:\", error);\n    }\n  }\n\n  // Get the entire database content\n  const fullData = await db.getData(\"/\");\n  console.log(\"Full database content:\\n\", JSON.stringify(fullData, null, 2));\n\n  console.log(\"\\nQuickstart example finished.\");\n}\n\nrunExample().catch(console.error);","lang":"typescript","description":"Demonstrates initializing the database, pushing data (including merging objects), retrieving data, and handling errors for non-existent paths. Requires Node.js ESM support."},"warnings":[{"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.","message":"All `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`.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Instantiate `JsonDB` with `new JsonDB(new Config('filename', autoSave, humanReadable, separator, syncWrites))`.","message":"Database initialization now *requires* the `Config` object in v2.0.0. Passing arguments directly to the `JsonDB` constructor is no longer supported.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"To merge objects or arrays instead of overwriting, use `await db.push('/path', newData, false);`.","message":"The `push` method will overwrite existing data at a given `DataPath` by default. Merging requires explicitly setting the third argument to `false`.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Be aware that primitives cannot be merged; they are always replaced. Plan your data structures accordingly if deep merging is critical.","message":"When 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.","severity":"gotcha","affected_versions":">=2.0.0"},{"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.","message":"Attempting to retrieve data using `getData` from a `DataPath` that does not exist will throw a `DataError`.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Upgrade to `node-json-db@2.4.2` or higher to restore correct class exports and resolve import issues.","message":"In 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.","severity":"gotcha","affected_versions":"2.4.0, 2.4.1"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"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.","cause":"You are attempting to retrieve data using `db.getData()` from a path that does not exist in the database.","error":"Error: DataPath '/your/non/existent/path' doesn't exist. Failed at /your."},{"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';`.","cause":"Incorrect `import` or `require()` syntax, often trying to use CommonJS `require()` with this ESM-first package, or incorrect named import for `JsonDB`.","error":"TypeError: JsonDB is not a constructor"},{"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);`.","cause":"You are calling `JsonDB` methods (which are `async`) outside of an `async` function or a top-level `await` context.","error":"SyntaxError: await is only valid in async functions and the top level bodies of modules"},{"fix":"Always initialize `Config` with `new Config(...)` when passing it to `JsonDB`, for example: `new JsonDB(new Config('filename', true, false, '/'))`.","cause":"You are attempting to instantiate the `Config` class without using the `new` keyword, which is required for JavaScript classes.","error":"TypeError: Class constructor Config cannot be invoked without 'new'"}],"ecosystem":"npm"}