Easy JSON Database
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.
Common errors
-
SyntaxError: Cannot use import statement outside a module
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`).fixEither 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');` -
TypeError: Cannot read properties of undefined (reading 'env')
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`.fixFor 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. -
Error: ENOENT: no such file or directory, open './some-database.json'
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.fixEnsure 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. -
JSON Parse Error: Unexpected token ... in JSON at position ...
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.fixInspect 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.
Warnings
- gotcha 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.
- breaking 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.
- gotcha 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.
- deprecated 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.
Install
-
npm install easy-json-database -
yarn add easy-json-database -
pnpm add easy-json-database
Imports
- Database
import Database from 'easy-json-database';
import { Database } from 'easy-json-database'; - Database (CommonJS)
const Database = require('easy-json-database'); - Database (TypeScript Type)
import { Database } from 'easy-json-database'; const db: Database = new Database('./data.json');
Quickstart
import { Database } from 'easy-json-database';
import { join } from 'path';
import { existsSync, unlinkSync, mkdirSync } from 'fs';
const dbPath = join(__dirname, 'my-test-database.json');
const backupsFolder = join(__dirname, 'backups');
// Ensure backups folder exists
if (!existsSync(backupsFolder)) {
mkdirSync(backupsFolder, { recursive: true });
}
// Clean up previous database file for a fresh start
if (existsSync(dbPath)) {
unlinkSync(dbPath);
}
const db = new Database(dbPath, {
snapshots: {
enabled: true,
interval: 60 * 60 * 1000, // 1 hour
folder: backupsFolder
}
});
async function runExample() {
console.log('Database initialized.');
// Set data
db.set('user:name', 'Alice');
console.log(`Set 'user:name' to 'Alice'.`);
// Get data
let username = db.get('user:name');
console.log(`Got 'user:name': ${username}`); // Output: Alice
// Add to a number
db.set('user:age', 25);
db.add('user:age', 5);
let age = db.get('user:age');
console.log(`User age after adding 5: ${age}`); // Output: 30
// Push to an array
db.set('items', ['apple']);
db.push('items', 'orange');
let items = db.get('items');
console.log(`Items after pushing 'orange': ${JSON.stringify(items)}`); // Output: ["apple","orange"]
// Check if key exists
console.log(`Does 'user:name' exist? ${db.has('user:name')}`); // Output: true
// Delete data
db.delete('user:name');
console.log(`Deleted 'user:name'. Does it exist now? ${db.has('user:name')}`); // Output: false
// Get all data
let allData = db.all();
console.log('All remaining data:', JSON.stringify(allData));
// Clear all data
db.clear();
console.log('Database cleared. All data:', JSON.stringify(db.all())); // Output: []
// Ensure cleanup of the database file after example
if (existsSync(dbPath)) {
unlinkSync(dbPath);
console.log(`Cleaned up database file: ${dbPath}`);
}
}
runExample().catch(console.error);