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 allows desktop applications to read and write files, save configurations, and even implement complex data management, just like traditional software.
File system operations
Electron allows you to use Node.js's built-in modules in the renderer process or the main process.fsThe module performs file operations.
Usage of the Node.js fs module
fsThese modules provide various file system operations, such as reading, writing, renaming, deleting, etc.
Example
const path = require('path');
// Get the current application path
const filePath = path.join(__dirname, 'data.txt');
// Read file asynchronously
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 Complete);
});
Parameter description:
fs.readFile(path, encoding, callback)Asynchronously reads file contents.fs.writeFile(path, data, callback): Write to a file (automatically creates it if it does not exist).path.join()Combines paths, cross-platform compatible.
File watching
You can usefs.watchReal-time monitoring of file changes, for example, to detect updates to configuration files or data files:
fs.watch(filePath, (eventType, filename) => {
console.log(`文件变化类型: ${eventType}`);
console.log(`变化的文件: ${filename}`);
});
Application directory path
Electron providesapp.getPath(name)Method 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 applications typically need to save user configurations, caches, 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, remains after the application is closed.sessionStorage: Session-level storage, cleared when the window is closed.
IndexedDB database
Suitable for storing structured data, applicable to offline applications:
Example
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 });
};
electron-store usage
electron-storeis the most convenient configuration repository, automatically persisted based on JSON.
Installation:
npm install electron-store
Usage example:
Example
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 saved to user data directory;
- JSON format, intuitive and easy to edit;
- Suitable for small persistent storage (settings, caches, etc.).
Data persistence recommendations
| Scenarios | 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 the application needs to store large amounts of data or relational data, it can integrate a database.
SQLite integration
SQLite is the most commonly used embedded database for Electron applications.
Install dependencies:
npm install sqlite3
Example code:
Example
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);
});
LevelDB usage
LevelDB is a key-value database, suitable for caching and high-performance reads and writes.
Installation:
npm install level
Usage example:
Example
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 synchronization | realm-js |
| LokiJS | In-memory database | lokijs |
Comprehensive summary
In Electron, data storage solutions are flexible and diverse:
- Small data →
electron-store; - Big data →
SQLite; - Structured →
IndexedDB; - High-speed key-value →
LevelDB; - File-based →
fs + JSON。
This enables Electron applications to run lightweight while also handling complex business logic and data storage tasks.
other extensions