all.db: Simple JSON Database

raw JSON →
0.3.2 verified Wed Apr 22 auth: no javascript maintenance

all.db is a lightweight, file-based JSON database designed for simple data persistence in Node.js applications. It stores data as a single JSON file on the local filesystem, providing a straightforward key-value store interface. Currently at version 0.3.2, its release cadence appears slow, with the last notable activity several years ago, suggesting it is in a maintenance phase rather than active development. Key differentiators include its extreme simplicity, minimal API (set, get, delete), and built-in TypeScript type definitions. Unlike more robust databases, it is not designed for high-concurrency environments or very large datasets due to its synchronous file operations, which can block the event loop, and its approach of loading the entire database into memory. It's best suited for small-scale projects, local development, or simple configuration storage.

error ENOENT: no such file or directory, open '/path/to/non-existent-directory/my-app-data.json'
cause The directory specified for the database file does not exist.
fix
Ensure the directory path exists before initializing the Database. Use fs.mkdirSync(path.dirname(filePath), { recursive: true });.
error SyntaxError: Unexpected token '...' in JSON at position X
cause The underlying JSON database file is corrupted or contains invalid JSON syntax, often due to manual editing or abrupt program termination during a write.
fix
Manually inspect the database file (.json) for syntax errors. If the data is not critical, delete the file to start fresh. Implement robust error handling around db.set and db.get to catch and manage such errors gracefully, perhaps by backing up the file before writes.
error TypeError: Cannot read properties of undefined (reading 'set')
cause Attempting to call methods like `set` or `get` on an uninitialized or incorrectly initialized `Database` instance.
fix
Verify that const db = new Database('...'); is executed correctly and db is a valid Database object before calling any of its methods.
breaking This library performs synchronous file I/O operations (readFileSync, writeFileSync). In Node.js server environments, this can block the event loop, leading to performance bottlenecks and unresponsiveness under heavy load or concurrent requests.
fix For production applications requiring scalability or concurrency, consider an asynchronous database solution or a different lightweight database that uses non-blocking I/O. Use this library primarily for CLI tools, local development, or very low-traffic scenarios.
gotcha The entire database content is loaded into memory and written back on every 'set' or 'delete' operation. This makes it inefficient for large datasets (many MBs or GBs) and can lead to high memory consumption.
fix Limit its usage to small configuration files or datasets where the total size remains manageable (e.g., a few hundred KBs to a few MBs). Profile memory usage if dealing with larger data.
gotcha As a simple file-based database, 'all.db' does not inherently handle concurrent write operations gracefully. Multiple processes or asynchronous calls attempting to write to the same file simultaneously could lead to race conditions and data corruption.
fix Ensure that only one instance or controlled sequence of operations writes to the database file at any given time. Implement external locking mechanisms or queueing if concurrent writes are unavoidable in your application logic. For multi-process scenarios, a client-server database is essential.
gotcha Error handling for file system operations (e.g., permissions, disk space, invalid JSON format) is minimal or requires manual wrapping. Corruption of the underlying JSON file due to unexpected termination or external modification can lead to application crashes or loss of data.
fix Always wrap database operations in `try-catch` blocks. Implement robust backup strategies for critical data. Validate input and output where possible to prevent malformed data from being written. Ensure the process has appropriate write permissions to the database file's directory.
npm install all.db
yarn add all.db
pnpm add all.db

This example demonstrates how to initialize `all.db`, store and retrieve various types of data (including typed objects), update values, and delete entries. It also includes basic directory creation for the database file.

import { Database } from 'all.db';
import * as path from 'path';
import * as fs from 'fs';

// Ensure the directory exists, or create it
const dbDir = path.join(process.cwd(), 'data');
if (!fs.existsSync(dbDir)) {
  fs.mkdirSync(dbDir, { recursive: true });
}

const db = new Database(path.join(dbDir, 'my-app-data.json'));

interface User {
  id: string;
  name: string;
  email: string;
}

async function runExample() {
  // Set data
  db.set('settings', { theme: 'dark', notifications: true });
  db.set<User>('user:123', { id: '123', name: 'Alice', email: 'alice@example.com' });
  db.set('lastLogin', new Date().toISOString());

  // Get data
  const settings = db.get('settings');
  console.log('Settings:', settings);

  const alice = db.get<User>('user:123');
  console.log('Alice:', alice);

  // Update data
  if (settings) {
    settings.notifications = false;
    db.set('settings', settings);
  }
  console.log('Updated settings:', db.get('settings'));

  // Delete data
  db.delete('lastLogin');
  console.log('Last login after delete:', db.get('lastLogin'));

  // Check if a key exists
  console.log('Does user:123 exist?', db.has('user:123'));
  console.log('All data:', db.all());
}

runExample().catch(console.error);