Registry / database / sql.js

sql.js

JSON →
library1.14.1jsnpmunverified

SQLite compiled to JavaScript via Emscripten, enabling full SQLite functionality in browsers and Node.js without native bindings. Current stable version is 1.14.1, released periodically. Key differentiator: runs entirely in memory using WebAssembly (or legacy JS), allows importing/exporting SQLite database files as Uint8Array, and works cross-platform without native dependencies. Includes contributed math/string extension functions. Note: unlike native SQLite bindings (e.g., sqlite3), sql.js requires loading the entire database into memory, which can cause out-of-memory issues for large databases. Pure JavaScript implementation with WebAssembly fallback.

npm install sql.js
INSTALL
IMPORT
SIG · SQL.JS
S
sql.js
databasejavascriptv1.14.1
harness data pending
Install & Compatibility
Where this runs

No compatibility data collected yet for this library.

Code
Verified usage

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

initSqlJs
✓ import initSqlJs from 'sql.js'
✗ const initSqlJs = require('sql.js')
Default export is a factory function that returns a promise of the SQL module. The require() pattern works in CommonJS but is not recommended for ESM projects. Always await the result before using SQL.
SQL (module object)
✓ const SQL = await initSqlJs({ locateFile: file => `/path/${file}` })
✗ const SQL = initSqlJs()
initSqlJs returns a Promise that resolves to the SQL module. Forgetting to await leads to undefined. The locateFile configuration is required in browsers to find the .wasm file; can be omitted in Node.js if the wasm binary is in the expected location.
Database
✓ const db = new SQL.Database();
✗ const db = new Database(); // ReferenceError
Database class is accessed via the SQL module object (e.g., SQL.Database). Cannot be imported as a named export directly. Always use SQL.Database after initializing the module.
Statement (prepared)
✓ const stmt = db.prepare('SELECT * FROM test');
✗ const stmt = new SQL.Statement('SELECT * FROM test');
Statements are created via db.prepare(), not by constructing a Statement class directly. The Statement class is internal and not exported.

Demonstrates creating an in-memory SQLite database, running statements, using prepared statements with parameter binding, and exporting the database as a Uint8Array.

import initSqlJs from 'sql.js'; async function main() { const SQL = await initSqlJs({ locateFile: file => `https://sql.js.org/dist/${file}` }); const db = new SQL.Database(); db.run("CREATE TABLE test (id INT, name TEXT);"); db.run("INSERT INTO test VALUES (1, 'Alice');"); db.run("INSERT INTO test VALUES (2, 'Bob');"); const stmt = db.prepare("SELECT * FROM test WHERE id > :id"); stmt.bind({ ':id': 0 }); while (stmt.step()) { const row = stmt.getAsObject(); console.log(row.id, row.name); } stmt.free(); const data = db.export(); const buffer = Buffer.from(data); console.log('Exported db size:', buffer.length); db.close(); } main().catch(console.error);
Debug
Known issues
gotchaThe database is stored in memory only; changes are not persisted unless manually exported via db.export() and saved to disk/indexedDB.
fix
Call db.export() to get a Uint8Array and persist it (e.g., write to file or localStorage). To import, pass the Uint8Array to new SQL.Database(data).
affects: >=1.0
breakingIn version 1.0, the API changed from callback-based to Promise-based: initSqlJs() now returns a Promise.
fix
Use await initSqlJs() or .then() instead of passing a callback.
affects: <1.0 -> >=1.0
gotchaIn browsers, the WebAssembly binary (sql-wasm.wasm) must be served as a static asset or loaded via CDN. Failing to provide locateFile will cause initSqlJs() to fail with a network error.
fix
Set locateFile property in initSqlJs config to point to the correct URL or local path of the .wasm file.
affects: >=1.0
deprecatedThe old non-WASM JavaScript fallback (sql.js) is deprecated; always use the WebAssembly version for better performance.
fix
Use the default WebAssembly build (sql-wasm.js) by importing 'sql.js' which now uses WASM. For legacy browsers, use the 'sql-asm.js' variant explicitly.
affects: <1.5
gotchaPrepared statements must be freed manually (stmt.free()) to avoid memory leaks. Failure to do so accumulates resource usage.
fix
Always call stmt.free() after processing all rows, or use try/finally to ensure cleanup.
affects: >=1.0
gotchaIn Node.js, the wasm binary may not be found automatically if installed globally or via a package manager that flattens node_modules. This can cause 'Error: Could not locate the wasm binary'.
fix
Explicitly set locateFile in initSqlJs options, or ensure the wasm file is in the expected path relative to the script.
affects: >=1.0
Errors
Common errors & fixes
TypeError: SQL is not a constructor
Forgot to await initSqlJs() or assigned the result incorrectly.
fix
const SQL = await initSqlJs({ locateFile: ... });
RuntimeError: memory access out of bounds
Corrupted or incompatible wasm binary, or using a version mismatch between js and wasm files.
fix
Ensure the .wasm file matches the sql.js version. Use the same source for both (e.g., from npm).
Error: Could not locate the wasm binary
The locateFile callback returned an incorrect path, or the binary is missing.
fix
Provide a valid locateFile function that returns the correct URL or local path to sql-wasm.wasm.
Uncaught (in promise) ReferenceError: SharedArrayBuffer is not defined
Using sql.js in an environment where SharedArrayBuffer is not available (e.g., older browsers, or non-secure contexts).
fix
Use the legacy JavaScript build (sql-asm.js) instead of the WASM build, or ensure the environment supports SharedArrayBuffer (requires cross-origin isolation headers).
Upgrade
Version history
1.14.1latest on npm
Audit
Dependencies
emscriptenoptionalUsed to compile SQLite to WebAssembly/JavaScript; required at build time, but not at runtime.
Agent activity
6 hits · last 30 days
node
4
OpenAI (training)
1
Resources
packagesql.js ↗
sql.js — npm install sql.js · libregistry