JDB File-Append-Only Database

0.5.5 · active · verified Wed Apr 22

JDB is a lightweight, file-append-only, in-memory, non-blocking I/O database inspired by NeDB. It allows users to manipulate data directly using standard JavaScript code, eliminating the need for a separate query language. The current stable version is 0.5.5, indicating a relatively mature but perhaps slower-paced development cycle without explicit release cadence information. Key differentiators include its lightweight core (approx. 200 lines), direct JavaScript data manipulation, promise support, and both standalone server and in-application library modes. It operates by appending JavaScript commands to a file, which are then re-executed on startup to reconstruct the database's in-memory state. Periodically, the database file can be compacted into a single JSON object to optimize storage and startup time.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates initializing a JDB instance, saving complex JavaScript objects using both callback and promise-based `exec` methods, accessing the saved data directly from the in-memory document, and finally simulating a restart to confirm data persistence by re-initializing from the saved file. It also includes cleanup of the temporary database file.

const jdb = require('jdb')();
const path = require('path');
const fs = require('fs');

const dbFilePath = path.join(__dirname, 'temp.jdb');

const some_data = {
    "name": {
        "first": "Yad",
        "last": "Smood"
    },
    "fav_color": "blue",
    "languages": [
        { "name": "Chinese", "level": 10 },
        { "name": "English", "level": 8, "preferred": true },
        { "name": "Japanese", "level": 6 }
    ],
    "height": 180,
    "weight": 68
};

async function runQuickstart() {
    // Clean up previous runs
    if (fs.existsSync(dbFilePath)) {
        fs.unlinkSync(dbFilePath);
    }

    try {
        // Initialize JDB with a specific file path
        await jdb.init({ dbPath: dbFilePath });
        console.log('Database initialized at:', dbFilePath);

        // Set data using exec with callback (converted to promise for sequential execution)
        await new Promise((resolve, reject) => {
            jdb.exec(
                {
                    data: some_data,
                    command: (jdbInstance, data) => {
                        jdbInstance.doc.ys = data;
                        jdbInstance.save('saved_data'); // Save with a return value
                    },
                    callback: (err, result) => {
                        if (err) return reject(err);
                        console.log('Exec with callback result:', result); // Expected: 'saved_data'
                        resolve(result);
                    }
                }
            );
        });

        // Simple way to save data using exec with promise
        await jdb.exec(some_data, (jdbInstance, data) => {
            jdbInstance.doc.arr = data.languages.map((el) => el.name);
            jdbInstance.save(); // Default save returns undefined on success
        });
        console.log('Second data save completed.');

        // Get the value after operations complete from the current instance
        console.log('Current instance: jdb.doc.ys.name:', jdb.doc.ys.name); 
        console.log('Current instance: jdb.doc.arr:', jdb.doc.arr);

        // Simulate restart by creating a new JDB instance and initializing from the same file
        const jdb2 = require('jdb')();
        await jdb2.init({ dbPath: dbFilePath });
        console.log('\n--- After simulated restart ---');
        console.log('New instance: jdb2.doc.ys.name:', jdb2.doc.ys.name);
        console.log('New instance: jdb2.doc.arr:', jdb2.doc.arr);

    } catch (err) {
        console.error('An error occurred:', err);
    } finally {
        // Clean up the database file
        if (fs.existsSync(dbFilePath)) {
            fs.unlinkSync(dbFilePath);
            console.log('\nCleaned up database file:', dbFilePath);
        }
    }
}

runQuickstart();

view raw JSON →