CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-node-json-db

Database using JSON file as storage for Node.JS

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

database-operations.mddocs/

Database Operations

Core CRUD operations for managing data in the JSON database, including data retrieval, storage, updates, and deletion with DataPath navigation.

Capabilities

Data Retrieval

Get Data

Retrieves data at the specified DataPath.

/**
 * Get the wanted data
 * @param dataPath - Path of the data to retrieve (e.g., "/users/1/name")
 * @returns Promise resolving to the data at the path
 * @throws DataError when path doesn't exist
 */
getData(dataPath: string): Promise<any>;

Usage Examples:

import { JsonDB, Config } from "node-json-db";

const db = new JsonDB(new Config("database.json"));

// Get entire object
const user = await db.getData("/users/1");

// Get specific property
const userName = await db.getData("/users/1/name");

// Get array
const tags = await db.getData("/posts/1/tags");

// Get root data
const allData = await db.getData("/");

Get Typed Object

Same as getData but with TypeScript type safety.

/**
 * Same as getData only here it's directly typed to your object
 * @param dataPath - Path of the data to retrieve
 * @returns Promise resolving to typed data
 */
getObject<T>(dataPath: string): Promise<T>;

Usage Examples:

interface User {
  name: string;
  email: string;
  age: number;
}

// Get with type safety
const user = await db.getObject<User>("/users/1");
console.log(user.name); // TypeScript knows this is a string

// Get array with typing
const users = await db.getObject<User[]>("/users");

Get Object with Default

Retrieves data with a fallback default value when the path doesn't exist.

/**
 * Same as getData but with your own object type and a possible default value when we can't find the data path
 * @param dataPath - Path of the data to retrieve
 * @param defaultValue - Value to use when the dataPath doesn't lead to data
 * @returns Promise resolving to data or default value
 * @throws DataError for errors other than path not found
 */
getObjectDefault<T>(dataPath: string, defaultValue?: T): Promise<T>;

Usage Examples:

// Get with default value
const settings = await db.getObjectDefault("/user/1/settings", {
  theme: "light",
  notifications: true
});

// Get array with empty array default
const posts = await db.getObjectDefault<Post[]>("/user/1/posts", []);

Check Existence

Checks if a DataPath exists without retrieving the data.

/**
 * Check for existing datapath
 * @param dataPath - Path to check for existence
 * @returns Promise resolving to true if path exists, false otherwise
 */
exists(dataPath: string): Promise<boolean>;

Usage Examples:

// Check before accessing
if (await db.exists("/users/1")) {
  const user = await db.getData("/users/1");
}

// Conditional operations
const hasSettings = await db.exists("/users/1/settings");
if (!hasSettings) {
  await db.push("/users/1/settings", { theme: "light" });
}

Data Modification

Push Data

Stores or updates data at the specified DataPath. Can override existing data or merge with it.

/**
 * Pushing data into the database
 * @param dataPath - Path leading to the data
 * @param data - Data to push
 * @param override - Overriding or not the data, if not, it will merge them (default: true)
 * @returns Promise that resolves when operation completes
 * @throws DataError for type mismatches during merge operations
 */
push(dataPath: string, data: any, override?: boolean): Promise<void>;

Usage Examples:

// Create new data (override mode - default)
await db.push("/users/1", {
  name: "Alice",
  email: "alice@example.com",
  age: 25
});

// Update specific property
await db.push("/users/1/age", 26);

// Merge mode - combines with existing data
await db.push("/users/1", { 
  active: true,
  lastLogin: new Date()
}, false);

// Merge arrays
await db.push("/users/1/tags", ["premium"], false);
// Results in concatenation: existing tags + ["premium"]

// Create nested structure automatically
await db.push("/posts/1/comments/0", {
  author: "Bob",
  text: "Great post!"
});

Merge Behavior:

  • Objects: Properties are merged recursively
  • Arrays: New array elements are concatenated to existing array
  • Primitives: Cannot be merged, will throw DataError

Delete Data

Removes data at the specified DataPath.

/**
 * Delete the data
 * @param dataPath - Path leading to the data to delete
 * @returns Promise that resolves when deletion completes
 */
delete(dataPath: string): Promise<void>;

Usage Examples:

// Delete specific property
await db.delete("/users/1/temporaryField");

// Delete entire object
await db.delete("/users/1");

// Delete array element
await db.delete("/posts/1/comments/0");

// Clear entire database
await db.delete("/");

Database Management

Load Database

Manually loads the database from storage. Called automatically on first data access.

/**
 * Manually load the database
 * It is automatically called when the first getData is done
 * @returns Promise that resolves when loading completes
 * @throws DatabaseError if loading fails
 */
load(): Promise<void>;

Save Database

Manually saves the database to storage.

/**
 * Manually save the database
 * By default you can't save the database if it's not loaded
 * @param force - Force the save of the database even if not loaded
 * @returns Promise that resolves when saving completes
 * @throws DatabaseError if saving fails
 */
save(force?: boolean): Promise<void>;

Usage Examples:

// Configure for manual saving
const db = new JsonDB(new Config("database.json", false)); // saveOnPush = false

// Make changes
await db.push("/users/1", userData);
await db.push("/users/2", userData2);

// Save manually
await db.save();

// Force save even if not loaded
await db.save(true);

Reload Database

Reloads the database from storage, discarding any unsaved changes.

/**
 * Reload the database from the file
 * @returns Promise that resolves when reloading completes
 */
reload(): Promise<void>;

Usage Examples:

// Discard changes and reload from file
await db.reload();

// Useful for multi-process scenarios
setInterval(async () => {
  await db.reload(); // Refresh every 30 seconds
}, 30000);

Reset Data

Directly resets the entire database content. Use with caution.

/**
 * Only use this if you know what you're doing.
 * It reset the full data of the database.
 * @param data - New data to replace entire database content
 */
resetData(data: any): void;

Usage Examples:

// Reset to empty database
db.resetData({});

// Replace with new structure
db.resetData({
  users: {},
  posts: {},
  settings: { version: "1.0" }
});

DataPath Syntax

DataPaths use a slash-separated syntax similar to XMLPath:

  • Root: / - Entire database
  • Object property: /users - Access the "users" property
  • Nested property: /users/1/name - Access nested properties
  • Array element: /users/0 - Access array by index
  • Array operations: /users[] - Append to array
  • Negative index: /users[-1] - Last element
  • Multi-dimensional: /matrix[0][1] - 2D array access

Examples:

// Given data structure:
{
  "users": [
    { "name": "Alice", "posts": [1, 2, 3] },
    { "name": "Bob", "posts": [4, 5] }
  ],
  "settings": {
    "theme": "dark",
    "notifications": true
  }
}

// DataPath examples:
"/users/0/name"           // "Alice"
"/users/1/posts/0"        // 4
"/settings/theme"         // "dark"
"/users/0/posts[]"        // Append to Alice's posts
"/users[-1]"              // Last user (Bob)

docs

adapters.md

advanced-features.md

database-operations.md

index.md

tile.json