{"id":16321,"library":"cozo-node","title":"CozoDB for Node.js","description":"Cozo-node is a Node.js binding for CozoDB, an embedded Datalog and graph database. It provides direct native access to CozoDB's capabilities, allowing developers to embed a powerful, relational-like database engine directly within their Node.js applications. The current stable version is 0.7.6, with recent minor releases indicating active development. Cozo-node differentiates itself by offering various storage engines, including in-memory ('mem'), SQLite, and RocksDB (depending on compile-time flags), enabling flexible persistence options. It exposes a simple API for running Datalog queries, managing relations, and handling database backups and restores. While primarily accessed via JavaScript/TypeScript, its underlying implementation is in Rust, providing high performance and low-level control. This library is suitable for applications requiring an embedded, queryable knowledge base or a lightweight graph database solution.","status":"active","version":"0.7.6","language":"javascript","source_language":"en","source_url":"https://github.com/cozodb/cozo-lib-nodejs","tags":["javascript","database","datalog","graph","typescript"],"install":[{"cmd":"npm install cozo-node","lang":"bash","label":"npm"},{"cmd":"yarn add cozo-node","lang":"bash","label":"yarn"},{"cmd":"pnpm add cozo-node","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This is the preferred ES Module import for TypeScript and modern JavaScript environments. CozoDb is a named export.","wrong":"import CozoDb from 'cozo-node';","symbol":"CozoDb","correct":"import { CozoDb } from 'cozo-node';"},{"note":"This is the correct CommonJS `require` pattern. The module exports CozoDb as a named property.","wrong":"const CozoDb = require('cozo-node');","symbol":"CozoDb","correct":"const { CozoDb } = require('cozo-node');"},{"note":"Imports the entire module's exports into a namespace object. You would then access the class as `CozoNode.CozoDb`.","symbol":"* as CozoNode","correct":"import * as CozoNode from 'cozo-node';"}],"quickstart":{"code":"import { CozoDb } from 'cozo-node';\n\nasync function main() {\n    const db = new CozoDb('mem'); // Use 'mem' for in-memory, 'sqlite' for persistent storage\n    try {\n        console.log('Inserting initial data...');\n        await db.run(\"?[] <- [['hello', 'world!'], ['cozo', 'database']]\");\n\n        console.log('Querying all data...');\n        const result1 = await db.run(\"?[a, b] <- [[a, b]]\");\n        console.log(\"Result of '?[a, b] <- [[a, b]]':\", result1);\n\n        console.log('Querying with parameters...');\n        const result2 = await db.run(\"?[message] <- [['hello', $name]]\", { \"name\": \"JavaScript\" });\n        console.log(\"Result of '?[message] <- [['hello', $name]]':\", result2);\n\n        console.log('Creating and querying a relation...');\n        await db.run(`\n            :create parent {child, parent}\n            :insert parent <- [['Alice', 'Bob'], ['Bob', 'Charlie']]\n        `);\n        const ancestors = await db.run(`\n            ?[ancestor] := parent{child, parent}, ancestor = parent\n            :union\n            ?[ancestor] := parent{child, intermediate}, ancestor_rec{intermediate, ancestor}\n        `, { child: 'Alice' });\n        console.log(\"Ancestors of Alice:\", ancestors);\n\n    } catch (err: any) {\n        console.error(\"Database operation failed:\", err.display || err.message);\n    } finally {\n        console.log(\"Closing database connection.\");\n        db.close();\n        console.log(\"Database connection closed.\");\n    }\n}\n\nmain();","lang":"typescript","description":"This quickstart demonstrates how to initialize an in-memory CozoDb instance, perform basic data insertion, query data with and without parameters, and execute more complex Datalog queries with relations, ensuring proper database closure."},"warnings":[{"fix":"Always ensure `db.close()` is called for every `CozoDb` instance when it's no longer needed, typically within a `finally` block or a resource cleanup hook.","message":"Failure to call `db.close()` on a CozoDb instance will lead to native resource leaks and may prevent the Node.js process from exiting cleanly.","severity":"gotcha","affected_versions":">=0.4.0"},{"fix":"If `npm install` fails with a binary-related error, you may need to compile the package from source. This requires a Rust toolchain. Refer to the 'Building' section in the package's README for detailed instructions.","message":"Precompiled binaries for `cozo-node` may not be available for all operating systems, architectures, or Node.js versions.","severity":"gotcha","affected_versions":">=0.4.0"},{"fix":"If trigger activation is essential for imported data, use regular Datalog queries with parameters for data insertion, as these will correctly activate any associated triggers.","message":"The `importRelations` and `importRelationsFromBackup` methods bypass triggers; any triggers defined on the imported relations will not be executed during these operations.","severity":"gotcha","affected_versions":">=0.4.0"},{"fix":"Ensure the `CozoDb` instance is newly created or completely empty before attempting a `restore` operation. For existing databases, consider using `importRelationsFromBackup` if specific relations need to be merged.","message":"The `restore` method is designed for initializing an empty database; it will fail if the current database instance already contains any data.","severity":"gotcha","affected_versions":">=0.4.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Install a Rust toolchain (`rustup.rs`) and then try installing the package with `npm install --build-from-source cozo-node` or by following the manual build steps in the README.","cause":"The `cozo-node` package could not find a prebuilt native binary matching your system's operating system, architecture, or Node.js version.","error":"Error: No precompiled binaries for your platform."},{"fix":"For ES Modules, use `import { CozoDb } from 'cozo-node';`. For CommonJS, use destructuring: `const { CozoDb } = require('cozo-node');`.","cause":"This error typically occurs when trying to use a default import for `CozoDb`, which is a named export, or incorrect CommonJS `require` syntax.","error":"TypeError: (0, _cozoNode.CozoDb) is not a constructor"},{"fix":"Examine the `err.display` or `err.message` property for specific CozoDB error details. Review your Datalog script and parameters for syntax, relation existence, and data consistency.","cause":"A Datalog query or database operation encountered a runtime error specific to CozoDB's internal logic, often due to malformed queries or data constraints.","error":"Database operation failed: <error message>"}],"ecosystem":"npm"}