Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readNode

Query SQLite using node:sqlite

Create a file-backed SQLite database in Node, bind values with prepared statements, and read rows in a separate process without installing a driver.

A small CLI needs to remember notes between runs. A local SQLite file gives you a place to append a note and read the list back in order. You can open that file with the SQLite module bundled with Node.

Open the file and bind a value

Save this as notes.mjs in a scratch directory. The script inserts a row when you pass a title and reads the saved rows on every run.

import { DatabaseSync } from "node:sqlite";

const db = new DatabaseSync("notes.db");
try {
  db.exec(`
    CREATE TABLE IF NOT EXISTS notes (
      id INTEGER PRIMARY KEY,
      title TEXT NOT NULL
    )
  `);

  const title = process.argv[2];
  if (title) {
    db.prepare("INSERT INTO notes (title) VALUES (?)").run(title);
  }

  const rows = db.prepare("SELECT title FROM notes ORDER BY id").all();
  for (const row of rows) console.log(row.title);
} finally {
  db.close();
}

The first run creates notes.db in the current working directory. IF NOT EXISTS lets subsequent runs reuse its table.

Use exec for the fixed table definition and a prepared statement for the insert. The ? is where SQLite binds the title. A title such as Ada's notes reaches SQLite as a value, so its apostrophe needs no SQL escaping. all() returns the result rows, and the query gives them an explicit order.

Read from a second process

Run the program once with a title and once with no argument. Keep both commands in the same directory so they open the same database file.

node notes.mjs "Ada's notes"
node notes.mjs

Each command writes Ada's notes to stdout. The second process reads the row left by the first.

On the Node 22 line, node:sqlite is available without the experimental flag from 22.13. On 22.5 through 22.12, pass --experimental-sqlite before the script name. Check the Node 22 SQLite docs for the version history. Node 22 can still print an experimental warning on stderr.

DatabaseSync performs the query on the calling thread. A short CLI can wait for it to finish. If you move the same code into a server and a query can hold up other requests, put the synchronous work on a worker thread.