Node.js LMDB Binding

0.10.1 · active · verified Wed Apr 22

node-lmdb provides a high-performance Node.js binding to LMDB (Lightning Memory-Mapped Database), a transactional key-value store renowned for its speed and efficiency. It operates as an in-process, zero-copy database, eliminating the overhead of socket communication. The library supports transactions, multiple databases within a single environment, and is designed for multi-threaded and multi-process use, offering crash-proof persistence. The current stable version is 0.10.1, with releases occurring periodically to address bugs and introduce features. Its key differentiators include direct memory-mapped access, support for binary and string values via Node.js Buffers, and an API designed to align with JavaScript conventions while maintaining parity with the underlying LMDB C API. It's suitable for applications requiring extremely fast, durable, local data storage.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize an LMDB environment, open a database, perform read and write operations within a transaction, and then properly close resources. It covers storing strings and binary data, and includes cleanup.

import { Env } from 'node-lmdb';
import * as fs from 'fs';
import * as path from 'path';

const dbPath = path.join(__dirname, 'mydata');
if (!fs.existsSync(dbPath)) {
    fs.mkdirSync(dbPath);
}

const env = new Env();
env.open({
    path: dbPath,
    mapSize: 2 * 1024 * 1024 * 1024, // 2GB maximum database size
    maxDbs: 5 // Allow up to 5 named databases
});

const dbi = env.openDbi({
    name: 'myPrettyDatabase',
    create: true // Create the database if it doesn't exist
});

try {
    let txn = env.beginTxn();
    const key1 = 1;
    let value1 = txn.getString(dbi, key1);
    
    console.log(`Initial value for key ${key1}: ${value1}`);

    if (value1 === null) {
        txn.putString(dbi, key1, "Hello from node-lmdb!");
        console.log(`Set value for key ${key1} to 'Hello from node-lmdb!'`);
    } else {
        txn.del(dbi, key1);
        console.log(`Deleted value for key ${key1}`);
    }
    
    const key2 = 'my_string_key';
    txn.putBinary(dbi, key2, Buffer.from('Binary data example'));
    console.log(`Put binary data for key '${key2}'`);

    txn.commit(); // Commit the transaction

    // Read the binary data back in a new transaction
    txn = env.beginTxn();
    const binaryValue = txn.getBinary(dbi, key2);
    console.log(`Retrieved binary data for key '${key2}': ${binaryValue?.toString()}`);
    txn.abort(); // Abort a read-only transaction

} catch (e) {
    console.error('LMDB operation failed:', e);
} finally {
    dbi.close();
    env.close();
    fs.rmSync(dbPath, { recursive: true, force: true }); // Clean up
}

view raw JSON →