Electron File System And Data Storage
In Electron, since it is based on Node.js, you can directly access the file system, database, and local storage.
This allows desktop applications to read and write files like traditional software, save configurations, and even implement complex data management.
* * *
## File System Operations
Electron allows you to perform file operations using Node.js's built-in `fs` module in the renderer process or main process.
### Using Node.js fs Module
The `fs` module provides various file system operations such as reading, writing, renaming, deleting, etc.
## Example
const fs = require('fs');
const path = require('path');
// Get current application path
const filePath = path.join(__dirname,'data.txt');
// Asynchronously read file
fs.readFile(filePath,'utf8',(err, data)=>{
if(err)throw err;
console.log('File Content:', data);
});
// Write file (overwrite)
fs.writeFile(filePath,'Hello Electron!',(err)=>{
if(err)throw err;
console.log('Write completed');
});
**Parameter Description:**
* `fs.readFile(path, encoding, callback)`: Asynchronously read file content.
* `fs.writeFile(path, data, callback)`: Write file (automatically creates if not exists).
* `path.join()`: Combine paths, cross-platform compatible.
### File Watching
You can use `fs.watch` to monitor file changes in real-time, for example to detect configuration file or data file updates:
fs.watch(filePath, (eventType, filename) => { console.log(`File change type: ${eventType}`); console.log(`Changed files: ${filename}`);});
### Application Directory Paths
Electron provides the `app.getPath(name)` method to get common system paths:
const { app } = require('electron'); console.log(app.getPath('home')); // User home directory console.log(app.getPath('desktop')); // Desktop path console.log(app.getPath('userData')); // Application data directory
These paths can be used to store logs, caches, or user configuration files.
* * *
## Local Data Storage
Electron applications often need to save user configurations, caches, or state information. Common storage methods include:
### localStorage and sessionStorage
Suitable for simple key-value pair data, such as theme settings, window state, etc.:
localStorage.setItem('theme', 'dark');const theme = localStorage.getItem('theme'); console.log(theme);
**Difference:**
* `localStorage`: Permanent storage, remains after closing the application.
* `sessionStorage`: Session-level storage, cleared when the window closes.
### IndexedDB Database
Suitable for storing structured data, applicable for offline applications:
## 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, automatically persisting 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');
**Advantages:**
* Automatically saves to user data directory;
* JSON format, intuitive and easy to edit;
* Suitable for small persistent storage (settings, caches, etc.).
### Data Persistence Solution Recommendations
| Scenario | Recommended Solution |
| --- | --- |
| Simple key-value pairs | electron-store |
| Structured data | IndexedDB |
| Large data files | fs + JSON files |
| Offline application database | SQLite or LevelDB |
* * *
## Database Integration
When applications need to store large or relational data, databases can be integrated.
### SQLite Integration
SQLite is the most commonly used embedded database for Electron applications.
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 read/write.
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 Scenario | Recommended Library |
| --- | --- | --- |
| MongoDB | Cloud sync, distributed | mongoose |
| MySQL | Relational big data | mysql2 |
| Realm | Mobile sync | realm-js |
| LokiJS | In-memory database | lokijs |
* * *
## Summary
In Electron, data storage solutions are flexible and diverse:
* Small data β `electron-store`;
* Large data β `SQLite`;
* Structured β `IndexedDB`;
* High-speed key-value β `LevelDB`;
* File-based β `fs + JSON`.
This allows Electron applications to run lightweight while also handling complex business logic and data storage tasks.
YouTip