Using IndexedDB with Electron

A simple database for your locale application, compatible with a web app.

Our demo use the Dexie.js interface to simplify the access to IndexedDB. You have just a small script to include in the app:

<script src="dexie.min.js"></script> 

Using IndexedDB, step by step

The code below is available in a fully workable electron app you can download. In this page, the source code is only displayed.

1) Create a database and define its schema

var db = new Dexie("MyDB")

db.version(1).stores({
  mytable: 'name,data'
})

This database had one table, "mytable", and two columns, "name" and "data".

2) Open the database

var err = document.getElementById("err")
err.innerHTML = "Database open"

db.open().catch(function(error) {
  err.innerHTML = "Can't open the database! Error:" + error
})

3) Add some entries

function sayAdded() {
  document.getElementById("added").innerHTML += "Record added!"
}

db.mytable.put({name: "x86", data: "8 MB RAM, 256 GB SSD"}).then(sayAdded)
db.mytable.put({name: "ARM", data: "2 MB RAM, 32 GB EMMC"}).then(sayAdded)

Rows are described as JS objects. The demo displays a message when a row is added, but this may be suppressed in the final app.

4) Retrieve the data

function showData(data) {
  document.getElementById("data").innerHTML += data[0].data
}

async function getData() {
  var result = await db.mytable.where('name').equals('ARM').toArray()
  showData(result)
}
getData()

We use async/away to be sure the data are available before to be processed (just displayed in this demo).

When and why use IndexedDB?

It is a standard way to store permanently large quantities of data and scripts, and retrieve them with queries... So it allow to get all the benefits of a database without installing anything!

Your database could be available to several applications (since they are on the same domain, localhost), the data are so shared. But it could have a drawback. When Chrome run out of hard drive space, it wipes out the whole database with no warning! You can lose all your data in a fraction of a second. You can avoid that by creating a persistent database with this command:

navigator.storage.persist()

This command is implemented in Chrome and so works for Electron, it does not apply to other browsers.

Type: electron main.js to run the demo.