Using IndexedDB with Electron
A simple database for a local application that is compatible with the web application.
Our demo uses the Dexie.js interface to simplify access to IndexedDB. You just need to include a small script in the application:
<script src="dexie.min.js"></script>
Using IndexedDB, step by step
The code below is available in a fully functional electronic download application. This page contains only source code.
1) Foundation and schema definition
var db = new Dexie("MyDB")
db.version(1).stores({
mytable: 'name,data'
})
This database has one table, "mytable," and two columns, "name" and "data."
2) Open 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 multiple 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)
Strings are described in JS objects. The demo displays a message when you add a row, but you can delete it in the target application .
4) Find 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()
Asynchronous/adventures are used to ensure that data is available before it is processed. In this demonstration, processing consists only in displaying them.
When and why to use IndexedDB
?This is a standard way to constantly store large amounts of data and scripts and get them using queries... Thus, this allows you to get all the benefits of the database without installing anything!
Your database will be accessible from multiple applications (since they are in the same domain, localhost), the data is shared. But there may be a downside to that. When Chrome runs out of hard disk space, it erases the entire database without warning! You can lose all data in a split second. This can be avoided by creating a permanent base using this command:
navigator.storage.persist()
This command is implemented in Chrome and therefore works with Electron, it does not apply to other browsers.
Enter: electron main.js to start the demo.