{"id":16342,"library":"easy-json-database","title":"Easy JSON Database","description":"Easy JSON Database (easy-json-database) is a lightweight, file-system based database solution for Node.js environments. Currently stable at version 1.5.1, it has seen no new releases in approximately three years, suggesting a maintenance-only status without active feature development. This package differentiates itself through its extreme simplicity, storing all data directly within a single JSON file. It offers basic CRUD operations (set, get, delete, has), numerical manipulations (add, subtract), and array operations (push), along with a `clear` and `all` method. Key features include an optional snapshot mechanism for backups. Unlike robust NoSQL databases (e.g., MongoDB, CouchDB) or relational databases with JSON capabilities (e.g., PostgreSQL), easy-json-database operates by loading and saving the entire JSON file to disk for every write operation, making it suitable only for small datasets and low-concurrency scenarios. It is primarily used in projects requiring minimal setup and direct file storage, such as the 'Scratch For Discord' bot.","status":"maintenance","version":"1.5.1","language":"javascript","source_language":"en","source_url":"https://github.com/Androz2091/easy-json-database","tags":["javascript","typescript"],"install":[{"cmd":"npm install easy-json-database","lang":"bash","label":"npm"},{"cmd":"yarn add easy-json-database","lang":"bash","label":"yarn"},{"cmd":"pnpm add easy-json-database","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary class 'Database' is exported as a named export. Ensure your project is configured for ESM or use dynamic import in CJS.","wrong":"import Database from 'easy-json-database';","symbol":"Database","correct":"import { Database } from 'easy-json-database';"},{"note":"This is the standard CommonJS import pattern shown in the documentation and is fully supported.","symbol":"Database (CommonJS)","correct":"const Database = require('easy-json-database');"},{"note":"The package ships with TypeScript type definitions, allowing for type-safe usage.","symbol":"Database (TypeScript Type)","correct":"import { Database } from 'easy-json-database';\nconst db: Database = new Database('./data.json');"}],"quickstart":{"code":"import { Database } from 'easy-json-database';\nimport { join } from 'path';\nimport { existsSync, unlinkSync, mkdirSync } from 'fs';\n\nconst dbPath = join(__dirname, 'my-test-database.json');\nconst backupsFolder = join(__dirname, 'backups');\n\n// Ensure backups folder exists\nif (!existsSync(backupsFolder)) {\n    mkdirSync(backupsFolder, { recursive: true });\n}\n\n// Clean up previous database file for a fresh start\nif (existsSync(dbPath)) {\n    unlinkSync(dbPath);\n}\n\nconst db = new Database(dbPath, {\n    snapshots: {\n        enabled: true,\n        interval: 60 * 60 * 1000, // 1 hour\n        folder: backupsFolder\n    }\n});\n\nasync function runExample() {\n    console.log('Database initialized.');\n\n    // Set data\n    db.set('user:name', 'Alice');\n    console.log(`Set 'user:name' to 'Alice'.`);\n\n    // Get data\n    let username = db.get('user:name');\n    console.log(`Got 'user:name': ${username}`); // Output: Alice\n\n    // Add to a number\n    db.set('user:age', 25);\n    db.add('user:age', 5);\n    let age = db.get('user:age');\n    console.log(`User age after adding 5: ${age}`); // Output: 30\n\n    // Push to an array\n    db.set('items', ['apple']);\n    db.push('items', 'orange');\n    let items = db.get('items');\n    console.log(`Items after pushing 'orange': ${JSON.stringify(items)}`); // Output: [\"apple\",\"orange\"]\n\n    // Check if key exists\n    console.log(`Does 'user:name' exist? ${db.has('user:name')}`); // Output: true\n\n    // Delete data\n    db.delete('user:name');\n    console.log(`Deleted 'user:name'. Does it exist now? ${db.has('user:name')}`); // Output: false\n\n    // Get all data\n    let allData = db.all();\n    console.log('All remaining data:', JSON.stringify(allData));\n\n    // Clear all data\n    db.clear();\n    console.log('Database cleared. All data:', JSON.stringify(db.all())); // Output: []\n\n    // Ensure cleanup of the database file after example\n    if (existsSync(dbPath)) {\n        unlinkSync(dbPath);\n        console.log(`Cleaned up database file: ${dbPath}`);\n    }\n}\n\nrunExample().catch(console.error);\n","lang":"typescript","description":"This quickstart demonstrates basic CRUD operations, numerical increments, array pushes, existence checks, and data clearing using `easy-json-database` in a TypeScript environment. It also shows how to configure snapshots and includes file system cleanup for a reproducible example."},"warnings":[{"fix":"For larger datasets, higher throughput, or concurrent access, consider using dedicated databases like `lowdb` (with an appropriate adapter), SQLite, or NoSQL solutions such as MongoDB or CouchDB. Avoid frequent, small write operations.","message":"Performance and Scalability Limitations: This database loads the entire JSON file into memory on initialization and writes the entire file back to disk on every modification. This design is highly inefficient for large datasets (typically > 10-100MB) or high-frequency write operations, leading to performance bottlenecks and high memory usage.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Implement robust backup strategies (like the built-in snapshots feature), ensure graceful application shutdowns, and consider external file-system level atomicity solutions if absolute data integrity is critical. For mission-critical data, avoid flat-file databases entirely.","message":"Data Corruption Risk: Due to its single-file storage mechanism, a partial write or unexpected application termination during a write operation can corrupt the entire JSON file, leading to complete data loss. There are no built-in transaction mechanisms to ensure atomic writes.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Ensure that only one instance of the application accesses the database file at a time, or implement external locking mechanisms (e.g., file locks) if multiple processes need to interact with the same database file. Design your application to avoid concurrent writes to the same key or file.","message":"Lack of Concurrency Control: Since the database operates on a single file, concurrent write attempts from multiple processes or even asynchronous operations within a single process can lead to race conditions and data overwrites.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Evaluate if the current feature set and stability meet your long-term project needs. For projects requiring active development, community support, or modern features, consider more actively maintained alternatives like `lowdb` or `node-json-db`.","message":"Limited Maintenance and Future Development: The package's last update was over three years ago (as of April 2026), indicating that it is in a maintenance-only state or potentially abandoned. Users should not expect new features, performance improvements, or timely bug fixes.","severity":"deprecated","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Either convert your project to ES Modules by adding `\"type\": \"module\"` to your `package.json` file or rename your file to `.mjs`, or use the CommonJS `require()` syntax: `const { Database } = require('easy-json-database');`","cause":"Attempting to use ES module `import` syntax in a CommonJS (CJS) Node.js project without proper configuration (e.g., `\"type\": \"module\"` in `package.json`).","error":"SyntaxError: Cannot use import statement outside a module"},{"fix":"For direct JSON file imports in TypeScript with ESM, ensure `\"resolveJsonModule\": true` and `\"esModuleInterop\": true` are set in `tsconfig.json`. Also, remember that direct JSON imports usually expose the entire JSON as a default export, or require specific import attributes (e.g., `import data from './data.json' with { type: 'json' }`) in native ESM environments.","cause":"Incorrectly importing a JSON file in an ES module context or misinterpreting the default export when TypeScript compiles ESM to CJS, typically when directly importing `.json` files without `resolveJsonModule` or `esModuleInterop`.","error":"TypeError: Cannot read properties of undefined (reading 'env')"},{"fix":"Ensure the directory path provided to the `Database` constructor exists and that your application has read/write permissions for that directory. You might need to create the directory programmatically using `fs.mkdirSync(path, { recursive: true })` before initializing the database.","cause":"The specified database file or its parent directory does not exist, or the application lacks the necessary write permissions to create it. This is a common file system error.","error":"Error: ENOENT: no such file or directory, open './some-database.json'"},{"fix":"Inspect the `.json` file for syntax errors using a JSON linter or validator. Common fixes include adding/removing commas, ensuring all keys and string values use double quotes, escaping special characters within strings, and balancing all brackets. If the file is corrupted, restore from a backup.","cause":"The underlying JSON file is malformed due to syntax errors (e.g., missing commas, unescaped quotes, trailing commas, unbalanced brackets, using single quotes instead of double quotes). This can happen from manual editing or corrupted writes.","error":"JSON Parse Error: Unexpected token ... in JSON at position ..."}],"ecosystem":"npm"}