WebSQL API Implementation for Node.js
This `websql` package provides a Node.js implementation of the deprecated WebSQL Database API, leveraging `sqlite3` for its backend operations. It enables developers to run code originally designed for browser-based WebSQL environments within a Node.js context, and also falls back to `window.openDatabase` when used in a browser via bundlers like Browserify or Webpack. The current stable version is 2.0.3, with no explicit release cadence specified, indicating a focus on stability and compatibility rather than active feature development. Its primary differentiator is its strict adherence to the existing WebSQL API as implemented in browsers, acting as a bridge for legacy applications rather than extending the standard. It specifically *does not* aim to invent new APIs, support features like BLOBs or encryption, or enhance WebSQL beyond its original scope, focusing instead on accurate emulation for compatibility.
Common errors
-
SQLITE_CANTOPEN: unable to open database file
cause The Node.js process lacks write permissions to the directory where the database file is being created, or the specified path is invalid.fixEnsure the Node.js process has appropriate write permissions to the specified database directory. Use an absolute path or a path relative to the process's working directory, or use `:memory:` for an in-memory database. -
TypeError: db.transaction is not a function
cause The `db` object returned by `openDatabase` might not be correctly initialized, or `openDatabase` failed to return a valid database instance.fixVerify that `openDatabase` completed successfully and returned a valid database object. Check for any errors during the `openDatabase` call and ensure you're calling transaction methods on the correctly initialized `db` object. -
Error: Cannot find module 'sqlite3'
cause `node-sqlite3`, the default backend for `websql`, is not installed as a dependency or failed to compile during installation.fixEnsure `sqlite3` is installed as a direct dependency: `npm install sqlite3`. If it's a native module compilation issue, verify your environment meets `node-gyp` requirements (e.g., Python, C++ build tools).
Warnings
- breaking The underlying WebSQL Database API is a deprecated standard and is not recommended for new development. This library is primarily intended for bridging legacy WebSQL code to Node.js environments.
- gotcha The `version`, `description`, and `size` parameters in `openDatabase()` are ignored by this library for compatibility reasons. Database versioning and migrations are not supported.
- gotcha This library does not extend the WebSQL API with new features such as `BLOB` support, encryption, or database deletion, strictly adhering to the original WebSQL specification.
- gotcha When used in the browser, this library transparently falls back to `window.openDatabase`, meaning its functionality is subject to the browser's native WebSQL support (which is deprecated and often limited to Chrome/Safari).
Install
-
npm install websql -
yarn add websql -
pnpm add websql
Imports
- openDatabase
const openDatabase = require('websql').openDatabase;import openDatabase from 'websql';
- customOpenDatabase
const customOpenDatabase = require('websql');import customOpenDatabase from 'websql/custom';
- Database
import { Database } from 'websql';const db = openDatabase('mydb.db', '1.0', 'description', 1);
Quickstart
import openDatabase from 'websql'; // Or `const openDatabase = require('websql');` for CommonJS
async function initializeDatabase() {
// Create a SQLite3 database file called 'mydb.db'
const db = openDatabase('mydb.db', '1.0', 'My Test Database', 1 * 1024 * 1024); // Size in bytes
console.log('Database opened successfully.');
// Perform a transaction to create a table and insert data
return new Promise((resolve, reject) => {
db.transaction((tx) => {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)',
[],
() => {
console.log('Table "users" created or already exists.');
tx.executeSql(
'INSERT INTO users (name, age) VALUES (?, ?)',
['Alice', 30],
() => {
console.log('Inserted Alice.');
tx.executeSql(
'INSERT INTO users (name, age) VALUES (?, ?)',
['Bob', 24],
() => {
console.log('Inserted Bob.');
tx.executeSql(
'SELECT * FROM users',
[],
(_, result) => {
console.log('Users:', Array.from(result.rows).map(row => row));
resolve(true);
},
(_, error) => {
console.error('Error selecting users:', error.message);
reject(error);
}
);
},
(_, error) => {
console.error('Error inserting Bob:', error.message);
reject(error);
}
);
},
(_, error) => {
console.error('Error inserting Alice:', error.message);
reject(error);
}
);
},
(_, error) => {
console.error('Error creating table:', error.message);
reject(error);
}
);
});
});
}
initializeDatabase().catch(console.error);