Database using JSON file as storage for Node.JS
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Core CRUD operations for managing data in the JSON database, including data retrieval, storage, updates, and deletion with DataPath navigation.
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("/");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");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", []);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" });
}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:
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("/");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>;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);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);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" }
});DataPaths use a slash-separated syntax similar to XMLPath:
/ - Entire database/users - Access the "users" property/users/1/name - Access nested properties/users/0 - Access array by index/users[] - Append to array/users[-1] - Last element/matrix[0][1] - 2D array accessExamples:
// 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)