browser-level

3.0.0 · active · verified Wed Apr 22

`browser-level` is a JavaScript library providing an `abstract-level` compliant database interface designed specifically for web browsers, utilizing IndexedDB as its backend. The current stable version is 3.0.0. It serves as the spiritual successor to `level-js`, offering a modern, `abstract-level`-compatible API for client-side data persistence. Releases typically align with major upgrades to its underlying `abstract-level` dependency, ensuring compatibility with the broader Level ecosystem. A key differentiator is its seamless integration with browser environments, providing first-class support for both Uint8Array and Buffer (via an optional shim) for keys and values. However, due to IndexedDB's inherent limitations, `browser-level` iterators do not offer strict snapshot guarantees across multiple `next()` or `nextv()` calls, which means concurrent writes might be visible to an ongoing iteration. This necessitates careful handling for applications requiring strict transactional isolation during iteration.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a `BrowserLevel` database, perform basic `put`, `batch`, `get`, and `iterator` operations, and properly open and close the database in a browser environment using TypeScript.

import { BrowserLevel } from 'browser-level';
import type { BatchOperation } from 'abstract-level';

async function runDbExample() {
  // Create a database called 'example' with JSON encoding
  const db = new BrowserLevel('example', { valueEncoding: 'json' });

  // Ensure the database is opened before operations
  await db.open();

  try {
    // Add an entry with key 'a' and value 1
    await db.put('a', 1);
    console.log('Put key 'a':', await db.get('a'));

    // Add multiple entries using batch
    const batchOperations: BatchOperation<string, number>[] = [
      { type: 'put', key: 'b', value: 2 },
      { type: 'put', key: 'c', value: 3 }
    ];
    await db.batch(batchOperations);
    console.log('Batch operations completed.');

    // Get value of key 'b'
    const valueB = await db.get('b');
    console.log('Value of key 'b':', valueB); // Expected: 2

    // Iterate entries with keys that are greater than 'a'
    console.log('Iterating entries > 'a':');
    for await (const [key, value] of db.iterator({ gt: 'a' })) {
      console.log(`  Key: ${key}, Value: ${value}`);
    } // Expected: b, 2 and c, 3

  } catch (error) {
    console.error('Database operation failed:', error);
  } finally {
    // Always close the database when done
    await db.close();
    console.log('Database closed.');
  }
}

runDbExample();

view raw JSON →