{"id":17173,"library":"bdb","title":"bdb (bcoin-org) - LevelDB Backend","description":"bdb is an embedded, low-level key-value database library specifically designed as a LevelDB backend for the bcoin full node Bitcoin implementation. It is built on top of `leveldown` (or compatible LevelDB bindings) to provide persistent storage. The package, currently at version 1.6.2, is part of the broader `bcoin-org` ecosystem, which appears to be under active maintenance, though `bdb` itself sees less frequent, direct updates. Its primary differentiator is the `bdb.key` utility, offering structured key encoding and decoding for managing complex data types common in blockchain applications, such as cryptographic hashes and integers, enabling efficient storage and retrieval. Unlike general-purpose LevelDB wrappers, `bdb` is tailored for the specific data structures and performance requirements of a Bitcoin node. It operates as a local, embedded database without a server component, similar to other NoSQL key-value stores. Release cadence is tied to the needs of the `bcoin` project, rather than independent frequent updates.","status":"maintenance","version":"1.6.2","language":"javascript","source_language":"en","source_url":"git://github.com/bcoin-org/bdb","tags":["javascript","database","db","leveldb"],"install":[{"cmd":"npm install bdb","lang":"bash","label":"npm"},{"cmd":"yarn add bdb","lang":"bash","label":"yarn"},{"cmd":"pnpm add bdb","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core LevelDB binding for Node.js; bdb acts as a wrapper/abstraction over it.","package":"leveldown","optional":false}],"imports":[{"note":"bdb is a CommonJS module and primarily consumed via `require()`. Direct ESM `import` statements are not supported.","wrong":"import bdb from 'bdb';","symbol":"bdb","correct":"const bdb = require('bdb');"},{"note":"The `create` method is accessed directly from the required bdb object to initialize a new database instance.","symbol":"bdb.create","correct":"const bdb = require('bdb');\nconst db = bdb.create('/path/to/my.db');"},{"note":"The `key` utility for structured key encoding/decoding is a static method on the main bdb object.","symbol":"bdb.key","correct":"const bdb = require('bdb');\nconst myKey = bdb.key('prefix', ['type1', 'type2']);"}],"quickstart":{"code":"const bdb = require('bdb');\nconst path = require('path');\nconst os = require('os');\nconst fs = require('fs/promises');\n\nasync function runDbExample() {\n  const dbPath = path.join(os.tmpdir(), `bdb-example-${Date.now()}`);\n  await fs.mkdir(dbPath, { recursive: true });\n  \n  const db = bdb.create(dbPath);\n\n  try {\n    await db.open();\n    console.log('Database opened at:', dbPath);\n\n    const myPrefix = bdb.key('r');\n    const myKey = bdb.key('t', ['hash160', 'uint32']);\n\n    const bucket = db.bucket(myPrefix.encode());\n    const batch = bucket.batch();\n\n    const hash = Buffer.alloc(20, 0x11); // Example 20-byte hash\n\n    // Write `foo` to `rt[11...11][00000000]`\n    batch.put(myKey.encode(hash, 0), Buffer.from('foo'));\n    batch.put(myKey.encode(Buffer.alloc(20, 0x22), 1), Buffer.from('bar'));\n\n    await batch.write();\n    console.log('Batch write complete.');\n\n    // Iterate:\n    const iter = bucket.iterator({\n      gte: myKey.min(),\n      lte: myKey.max(),\n      values: true\n    });\n\n    console.log('\\nIterating through records:');\n    await iter.each((key, value) => {\n      const [decodedHash, index] = myKey.decode(key);\n      console.log('  Key:', key.toString('hex'), '-> Hash:', decodedHash.toString('hex'), 'Index:', index, 'Value:', value.toString());\n    });\n    \n    await iter.end(); // Important to close iterator resources\n\n    // Using async iterator:\n    console.log('\\nIterating with async iterator:');\n    const asyncIter = bucket.iterator({\n      gte: myKey.min(),\n      lte: myKey.max(),\n      values: true\n    });\n\n    for await (const {key, value} of asyncIter) {\n      const [decodedHash, index] = myKey.decode(key);\n      console.log('  Key:', key.toString('hex'), '-> Hash:', decodedHash.toString('hex'), 'Index:', index, 'Value:', value.toString());\n    }\n\n    await db.close();\n    console.log('\\nDatabase closed.');\n  } catch (error) {\n    console.error('Database operation failed:', error);\n  } finally {\n    await fs.rm(dbPath, { recursive: true, force: true });\n    console.log('Cleaned up database directory:', dbPath);\n  }\n}\n\nrunDbExample();","lang":"javascript","description":"Demonstrates opening a bdb database, creating a bucket, encoding/decoding structured keys, performing batch writes, and iterating over stored key-value pairs using both callback-based and async iterators, then properly closing and cleaning up the database."},"warnings":[{"fix":"Always use `const bdb = require('bdb');` to import the module in both CommonJS and hybrid environments.","message":"bdb is a CommonJS module and does not natively support ES module `import` syntax. Attempting to `import bdb from 'bdb'` directly will result in runtime errors in an ESM context.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Strictly define and adhere to your `bdb.key` schemas. Always use the corresponding `bdb.key.encode()` for writing and `bdb.key.decode()` for reading data, ensuring types match the definition.","message":"Key encoding/decoding is central to bdb's design. Incorrectly defining `bdb.key` formats or attempting to read keys with a mismatched format will lead to data corruption or incorrect parsing, returning unexpected values or errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure all `db` instances are explicitly closed when no longer needed. Similarly, always call `iterator.end()` after completing iteration to release underlying resources, ideally within a `finally` block or using `for await...of` which handles iterator closing implicitly for async iterators.","message":"Not closing database instances (`db.close()`) or iterators (`iter.end()`) can lead to file descriptor leaks, corrupted databases, or resource exhaustion, especially in long-running applications.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"The main `bdb` export is an object. To create a database instance, use `bdb.create()`. For key utilities, use `bdb.key()`.","cause":"Attempting to call the `bdb` module itself as a function, often due to a misunderstanding of how the module's API is exposed.","error":"TypeError: bdb is not a function"},{"fix":"Ensure the Node.js process has read and write permissions for the database directory path provided to `bdb.create()`. Check directory ownership and permissions.","cause":"The application lacks write permissions to the specified database directory.","error":"Error: IO error: While open a file for appending: /path/to/my.db/LOG: Permission denied"},{"fix":"bdb is CommonJS. If your project is ESM, you might need to use dynamic `import('bdb')` or convert the surrounding code to CommonJS, or use a build tool to handle the interoperability.","cause":"You are attempting to use `require()` in an ES module environment where it's not directly compatible, or trying to `import` a CommonJS module incorrectly.","error":"ERR_REQUIRE_ESM: require() of ES Module ... not supported. Instead change the require of index.js in ... to a dynamic import() which is available in all CommonJS modules."}],"ecosystem":"npm","meta_description":null}