Registry / database / database-js

database-js

JSON →
library3.0.11jsnpmunverified

database-js provides a common, promise-based interface for SQL database access in JavaScript, inspired by the Java Database Connectivity (JDBC) API. It abstracts away the specifics of various underlying database drivers, allowing developers to interact with different databases (such as MySQL, PostgreSQL, SQLite, MS SQL Server, Firebase, CSV, Excel, JSON, and INI files) using a consistent API and connection string format. The library includes built-in support for prepared statements, even for drivers that don't natively offer them, and is designed to integrate seamlessly with ES7 async/await patterns. The current stable version is 3.0.11, and it receives regular maintenance updates for bug fixes. Its key differentiators include driver agnosticism via connection strings and a consistent promise-based API across heterogeneous data sources.

npm install database-js
INSTALL
IMPORT
SIG · DATABASE-JS
D
database-js
databasejavascriptv3.0.11
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Connection
import { Connection } from 'database-js'; // or const { Connection } = require('database-js');
import Connection from 'database-js'; // or const Connection = require('database-js');
The `Connection` class is a named export. While the documentation primarily shows CommonJS `require`, modern Node.js projects can use named ESM imports. Avoid default imports or importing the entire module without destructuring.
prepareStatement (via Connection instance)
const conn = new Connection(connectionString); const stmt = conn.prepareStatement(sql);
The `prepareStatement` method is accessed via an instantiated `Connection` object, not directly from the module export.
Driver (for custom drivers)
import { Driver } from 'database-js/lib/Driver'; // Example for custom driver development
import { Driver } from 'database-js'; // Driver class is not a top-level export
For developing custom drivers, the `Driver` base class might be needed, typically imported from a specific internal path, not the main package root. Most users will not need this.

This quickstart demonstrates how to establish a database connection, execute DDL, INSERT, UPDATE, and SELECT operations using prepared statements with the promise-based API, and properly close the connection. It highlights the unified interface across different database types.

import { Connection } from 'database-js'; // IMPORTANT: You must also install the specific driver package, e.g., 'npm install database-js-sqlite' async function runDatabaseOperations() { // Using SQLite as an example. Change the connection string // and install the relevant driver for other databases. const connectionString = "sqlite:///path/to/test.sqlite"; // Or mysql://user:password@localhost/test const conn = new Connection(connectionString); try { // COMMAND: Create a table await conn.prepareStatement( "CREATE TABLE IF NOT EXISTS city (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, population INTEGER)" ).execute(); console.log('Table created or already exists.'); // COMMAND: Insert data using a prepared statement const insertStmt = conn.prepareStatement("INSERT INTO city (name, population) VALUES (?, ?)"); await insertStmt.execute("Rio de Janeiro", 6747815); console.log('Inserted Rio de Janeiro.'); // QUERY: Select data using a prepared statement const queryStmt = conn.prepareStatement("SELECT * FROM city WHERE name = ?"); const results = await queryStmt.query("New York"); // Assuming 'New York' might exist from previous runs console.log('Query results for New York:', results); // ANOTHER COMMAND: Update data const updateStmt = conn.prepareStatement("UPDATE city SET population = population + ? WHERE name = ?"); await updateStmt.execute(1, "Rio de Janeiro"); console.log('Updated Rio de Janeiro population.'); // QUERY: Select all data const allCities = await conn.prepareStatement("SELECT * FROM city").query(); console.log('All cities:', allCities); } catch (reason) { console.error('An error occurred:', reason); } finally { // CLOSING THE CONNECTION await conn.close(); console.log('Connection closed.'); } } runDatabaseOperations();
Debug
Known issues
gotchadatabase-js is a core interface library. You must explicitly install separate driver packages (e.g., `database-js-sqlite`, `database-js-mysql`) for the specific database type you intend to use. The core package itself has no built-in drivers.
fix
Install the appropriate driver package for your database, e.g., `npm install database-js-sqlite`.
affects: >=1.0.0
gotchaConnection strings are critical for specifying the database type, host, credentials, and other connection parameters. An incorrectly formatted connection string will lead to driver not found errors or connection failures.
fix
Refer to the documentation for the specific `database-js` driver (e.g., `database-js-mysql` documentation) for the correct connection string format.
affects: >=1.0.0
gotchaAll database operations (query, execute, close) return Promises. Failing to use `await` or `.then().catch()` will result in unhandled promise rejections and operations not completing as expected, leading to difficult-to-debug asynchronous issues.
fix
Always `await` promise-returning methods or chain `.then()` and `.catch()` to handle successful completion and errors.
affects: >=1.0.0
breakingWhile not explicitly documented as a breaking change for `database-js` itself, historically, major version bumps (like v3) in Node.js libraries often introduce changes in module loading paradigms, potentially impacting how the library is imported (e.g., shifting primary support or default exports between CommonJS and ES Modules). Although the documentation shows CommonJS, modern tooling might expect ESM.
fix
If encountering issues with `require()` or `import` statements, verify your module resolution settings in `package.json` (e.g., `"type": "module"`) and ensure you are using named imports `{ Connection }` rather than default imports for ESM, or destructuring for CJS.
affects: >=3.0.0
gotchaThis library is primarily designed for server-side (Node.js) applications. While some drivers might theoretically work in a browser environment (e.g., `database-js-sqlite` if compiled to WebAssembly), directly connecting to SQL databases from client-side JavaScript is a significant security risk and highly discouraged due to exposure of credentials and direct database access.
fix
Always use `database-js` within a secure backend environment or a trusted, controlled desktop application (e.g., Electron). Never expose database connection details directly to a web browser client.
affects: >=1.0.0
Errors
Common errors & fixes
Error: No driver found for connection string: "mysql://..."
The specific `database-js` driver package for the database type in the connection string (e.g., `database-js-mysql`) has not been installed.
fix
Run `npm install <driver-package-name>`, e.g., `npm install database-js-mysql`.
TypeError: (0 , database_js__WEBPACK_IMPORTED_MODULE_0__.Connection) is not a constructor
This error typically occurs in bundled or transpiled environments (like Webpack or Babel) when trying to use CommonJS `require` syntax with a package that is treated as an ES Module, or when a named export is incorrectly imported as a default.
fix
Ensure you are using the correct named import: `import { Connection } from 'database-js';` for ESM, or `const { Connection } = require('database-js');` for CommonJS. Check your project's module resolution settings (`package.json#type`).
UnhandledPromiseRejectionWarning: Promise { <pending> }
A Promise returned by a `database-js` operation (like `query`, `execute`, or `close`) was not `await`ed or did not have a `.catch()` handler, leading to an unhandled rejection if an error occurred.
fix
Always use `await` with `async` functions for database operations, or attach a `.catch()` handler to every Promise: `stmt.query().catch(error => console.error(error));`.
TypeError: conn.prepareStatement is not a function
The `conn` object is not a valid `Connection` instance, likely due to an incorrect import or instantiation of the `Connection` class.
fix
Verify that `Connection` is imported correctly and `new Connection(connectionString)` is called to create the connection object.
Upgrade
Version history
3.0.11latest on npm
Audit
Dependencies
database-js-mysqloptionalRequired for connecting to MySQL databases.
database-js-postgresoptionalRequired for connecting to PostgreSQL databases.
database-js-sqliteoptionalRequired for connecting to SQLite databases.
database-js-mssqloptionalRequired for connecting to Microsoft SQL Server databases.
database-js-firebaseoptionalRequired for connecting to Firebase.
database-js-csvoptionalRequired for connecting to CSV files.
database-js-xlsxoptionalRequired for connecting to Excel (XLSX) files.
database-js-jsonoptionalRequired for connecting to JSON files.
database-js-inioptionalRequired for connecting to INI files.
database-js-adodboptionalRequired for connecting to ActiveX Data Objects (Windows only).
Agent activity
12 hits · last 30 days
node
12
Resources