Node.js SQLite

Summary: in this tutorial, you will learn how to interact with SQLite from a Node.js application using a built-in SQLite module.

Node.js 22.5.0 brought an experimental SQLite module under the name node:sqlite. In this tutorial, you will learn how to use the built-in node:sqlite module to insert, update, delete, and select data from a table in SQLite.

Prerequisites

  • Experienced with JavaScript.
  • Basic understanding of Node.js.
  • Familiar with SQLite (If not check out this SQLite tutorial).

Creating a new project

Step 1. Open your terminal and create a new directory to store the project:

mkdir sqlite-demoCode language: JavaScript (javascript)

Step 2. Navigate to the project directory:

cd sqlite-demoCode language: JavaScript (javascript)

Step 3. Initialize the project using the npm init command:

npm init --yCode language: JavaScript (javascript)

This command will create a package.json file in the project directory.

Step 4. Create an index.js file within the project directory. This will be the entry point of the Node.js application.

Step 5. Change the package.json file to support ES6 modules:

"type": "module",Code language: JavaScript (javascript)

And configure the npm start command in the scripts section:

"scripts": {
  "start": "node --experimental-sqlite index.js"
},Code language: JavaScript (javascript)

Note that the flag --experimental-sqlite is required because the built-in SQLite module is still experimental.

Step 6. Run the application using the npm start:

npm startCode language: JavaScript (javascript)

It’ll run the index.js with the --experimental-sqlite flag.

Opening a database connection

To open a connection to an SQLite database file, you use the DatabaseSync constructor:

const db = new DatabaseSync(location[, options])Code language: JavaScript (javascript)

The DatabaseSync constructor accepts two arguments:

  • location is a string that specifies the path to an SQLite file. If you want to use an in-memory database, you can pass the ::memory:: string.
  • options is a JavaScript object that species the connection options. It has an open property that accepts a boolean value. If the open is true, the database is opened by the DatabaseSync constructor. However, if it is false, you need to open the database manually y calling the open() method of the DatabaseSync object.

The following example shows how to open a connection to a database file (db.sqlite) located in the project directory:

import { DatabaseSync } from 'node:sqlite';

const db = new DatabaseSync('db.sqlite');Code language: JavaScript (javascript)

How it works.

First, import the DatabaseSync class from the node:sqlite module:

import { DatabaseSync } from 'node:sqlite';Code language: JavaScript (javascript)