Electron File System and Data Storage
In Electron, because it is based on Node.js, you can directly access the file system, databases, and local storage.
This lets desktop apps read/write files, save configurations, and even implement complex data management like traditional software.
File system operations
Electron allows you to use Node.js's built-in fs module for file operations in either the renderer or main process.
Using the Node.js fs module
fs The module provides a variety of file system operations, such as read, write, rename, delete, etc.
Example
const
fs
=
require
(
'fs'
)
;
const
path
=
require
(
'path'
)
;
// Get the current application path
const
filePath
=
path.
join
(
__dirname
,
'data.txt'
)
;
// Read a file asynchronously
fs.
readFile
(
filePath
,
'utf8'
,
(
err
,
data
)
=>
{
if
(
err
)
throw
err
;
console.
log
(
'File content:'
,
data
)
;
}
)
;
// Write a file (overwrite)
fs.
writeFile
(
filePath
,
'Hello Electron!'
,
(
err
)
=>
{
if
(
err
)
throw
err
;
console.
log
(
'Write complete'
)
;
}
)
;
Parameter Description:
fs.readFile(path, encoding, callback): read file content asynchronously.fs.writeFile(path, data, callback): write a file (created automatically if it does not exist).path.join(): join paths, cross-platform compatible.
File watching
You can use the fs.watch Watch file changes in real time, for example to detect updates to config or data files:
fs.watch(filePath, (eventType, filename) => {
console.log(`文件变化类型: ${eventType}`);
console.log(`变化的文件: ${filename}`);
});
Application directory paths
Electron provides app.getPath(name) methods to get common system paths:
const { app } = require('electron');
console.log(app.getPath('home')); // 用户主目录
console.log(app.getPath('desktop')); // 桌面路径
console.log(app.getPath('userData')); // 应用数据目录
These paths can be used to store logs, caches, or user configuration files.
Local data storage
Electron apps usually need to save user configuration, cache, or state information. Common storage methods include:
localStorage and sessionStorage
Suitable for simple key-value data, such as theme settings, window state, etc.:
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');
console.log(theme);
Difference:
localStorage: permanent storage, retained after the app is closed.sessionStorage: session-level storage, cleared when the window is closed.
IndexedDB database
Suitable for storing structured data, ideal for offline apps:
Example
const
request
=
indexedDB.
open
(
'myDatabase'
,
1
)
;
request.
onupgradeneeded
=
function
(
)
{
const
db
=
request.
result
;
db.
createObjectStore
(
'users'
,
{
keyPath
:
'id'
}
)
;
}
;
request.
onsuccess
=
function
(
)
{
const
db
=
request.
result
;
const
tx
=
db.
transaction
(
'users'
,
'readwrite'
)
;
const
store
=
tx.
objectStore
(
'users'
)
;
store.
put
(
{
id
:
1
,
name
:
'Alice'
,
age
:
25
}
)
;
}
;
Using electron-store
electron-store is the most convenient configuration storage library, with automatic persistence based on JSON.
Installation:
npm install electron-store
Usage example:
Example
const
Store
=
require
(
'electron-store'
)
;
const
store
=
new
Store
(
)
;
// Save configuration
store.
set
(
'user.name'
,
'Tom'
)
;
store.
set
(
'theme'
,
'dark'
)
;
// Read configuration
console.
log
(
store.
get
(
'user.name'
)
)
;
// Tom
// Delete configuration
store.
delete
(
'theme'
)
;
Fixed size, stores elements of the same type.
- Automatically saved to the user data directory;
- JSON format, intuitive and easy to edit;
- Suitable for small persistent storage (settings, cache, etc.).
Data persistence recommendations
| Scenario | Recommended solution |
|---|---|
| Simple key-value | electron-store |
| Structured data | IndexedDB |
| Large data files | fs + JSON file |
| Offline application database | SQLite or LevelDB |
Database integration
When an app needs to store large amounts of or relational data, you can integrate a database.
SQLite integration
SQLite is the most commonly used embedded database for Electron apps.
Install dependencies:
npm install sqlite3
Example code:
Example
const
sqlite3
=
require
(
'sqlite3'
)
.
verbose
(
)
;
const
db
=
new
sqlite3.
Database
(
'mydata.db'
)
;
// Create table
db.
run
(
"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)"
)
;
// Insert data
db.
run
(
"INSERT INTO users (name, age) VALUES (?, ?)"
,
[
'Alice'
,
25
]
)
;
// Query data
db.
all
(
"SELECT * FROM users"
,
[
]
,
(
err
,
rows
)
=>
{
if
(
err
)
throw
err
;
console.
log
(
rows
)
;
}
)
;
Using LevelDB
LevelDB is a key-value database, suitable for caching and high-performance reads/writes.
Installation:
npm install level
Usage example:
Example
const
level
=
require
(
'level'
)
;
const
db
=
level
(
'./mydb'
)
;
// Write data
await db.
put
(
'username'
,
'Bob'
)
;
// Read data
const
value
=
await db.
get
(
'username'
)
;
console.
log
(
value
)
;
Other database options
| Type | Applicable scenarios | Recommended library |
|---|---|---|
| MongoDB | Cloud sync, distributed | mongoose |
| MySQL | Relational big data | mysql2 |
| Realm | Mobile sync | realm-js |
| LokiJS | In-memory database | lokijs |
Comprehensive summary
In Electron, data storage options are flexible and varied:
- Small data ->
electron-store; - Large data ->
SQLite; - Structured ->
IndexedDB; - High-speed key-value ->
LevelDB; - File-based ->
fs + JSON.
This lets Electron apps run lightweight while also carrying complex business logic and data storage tasks.