File System and Local Data Storage
8 min read
When you build a web application, you are restricted to browser-based storage like localStorage, sessionStorage, or IndexedDB. If you try to save a 5GB video file into localStorage, the browser will laugh at you, crash, and your user will be very upset.
Building a desktop application with Electron changes the rules. You are no longer confined to the browser's sandbox. You have access to the user's actual hard drive. You can create files, read directories, save configuration settings, and embed entire SQL databases directly on the user's machine.
However, with great power comes the responsibility of not accidentally wiping out the user's C:\Windows directory. In this guide, we will explore the industry standards for managing the file system and local data in an Electron application.
1. Navigating App Directories: Using app.getPath() 🗺️
The Problem
If you want to save a user's avatar image, where do you put it? You might be tempted to hardcode a path like C:\Users\JohnDoe\Documents\MyApp. But what if the user is named Jane? What if they are using a Mac (/Users/Jane/...) or Linux (/home/jane/...)?
Hardcoding file paths is a guaranteed way to ensure your app only works on your specific computer and crashes everywhere else. Different operating systems have entirely different folder structures and permissions.
The Solution: app.getPath()
Electron provides a built-in method called app.getPath(name) that asks the underlying operating system for the correct, standard directory paths.
Definition: app.getPath() is a synchronous method available in the Main process that retrieves a path to a special directory or file associated with the given name.
Under the hood: When you call this function, Electron queries the OS-level environment variables (like %APPDATA% on Windows or ~/Library/Application Support on macOS) and returns the exact absolute string path.
Industry Standard Usage
In the industry, the most frequently used path is 'userData'. This is a directory specifically dedicated to your application where you can safely store databases, settings, and local files. The OS knows not to delete this unless the user uninstalls the app.
// main.js (Main Process)
const { app } = require('electron');
const path = require('path');
app.whenReady().then(() => {
// Get the safe, OS-specific directory for your app's data
const userDataPath = app.getPath('userData');
console.log('Your app data lives here:', userDataPath);
// Windows: C:\Users\<User>\AppData\Roaming\<YourAppName>
// macOS: ~/Library/Application Support/<YourAppName>
// Linux: ~/.config/<YourAppName>
// Now you can safely construct file paths inside it
const myDatabasePath = path.join(userDataPath, 'local-database.sqlite');
});Note: Never store heavy app data in app.getPath('desktop') unless you want your users to hate you for cluttering their workspace.
2. Reading and Writing Local Files via Main Process 📝
The Problem
Modern Electron apps use Context Isolation. This means the frontend UI (the Renderer process) operates like a normal web page. It is sandboxed. It cannot import Node.js modules like fs (File System) to read or write files.
If the Renderer could directly access the file system, any malicious script running in your app's UI could silently read a user's private documents and upload them to the internet.
The Solution: Inter-Process Communication (IPC)
To read or write a file, the Renderer must ask the Main process to do it.
Imagine you are at a high-end restaurant. You (the Renderer) are sitting at a table. You do not walk into the kitchen (the File System) to cook your own meal. You give your order to the waiter (IPC), who takes it to the chef (the Main Process). The chef safely prepares the food and the waiter brings it back to you.
Definition: We use Node's fs.promises module in the Main process to perform file operations, and expose a secure bridge (contextBridge) so the Renderer can request these operations.
Practical Implementation
Step 1: The Chef (Main Process - main.js)
We set up an IPC handler that listens for file write requests.
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs/promises'); // Use promises for clean async/await
async function handleFileSave(event, filename, content) {
try {
const userDataPath = app.getPath('userData');
const filePath = path.join(userDataPath, filename);
// Write the file to the disk
await fs.writeFile(filePath, content, 'utf-8');
return { success: true, path: filePath };
} catch (error) {
return { success: false, error: error.message };
}
}
app.whenReady().then(() => {
ipcMain.handle('save-local-file', handleFileSave);
const win = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
});
win.loadFile('index.html');
});Step 2: The Waiter (Preload Script - preload.js)
We define exactly what the UI is allowed to ask the Main process.
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('fileAPI', {
saveFile: (filename, content) => ipcRenderer.invoke('save-local-file', filename, content)
});Step 3: The Customer (Renderer Process - renderer.js / React / Vue)
The UI calls the exposed API.
// A user clicks a "Save Notes" button in your UI
async function saveUserNotes() {
const notes = "Buy groceries, conquer the world, learn Electron.";
const response = await window.fileAPI.saveFile('notes.txt', notes);
if (response.success) {
console.log(`Saved successfully at: ${response.path}`);
} else {
console.error(`Failed to save: ${response.error}`);
}
}3. Storing User Preferences and Settings Safely ⚙️
The Problem
Almost every app needs to remember user preferences: Is Dark Mode enabled? What is the default language? Did the user hide the sidebar?
You could use the fs module to write a settings.json file manually. However, manually reading, parsing, modifying, and stringifying JSON every time a setting changes is tedious. Furthermore, if your app crashes exactly while fs.writeFile is running, your settings.json becomes corrupted (half-written), and your app will permanently crash on the next startup.
The Solution: electron-store
Instead of reinventing the wheel, the industry standard is to use robust, battle-tested libraries designed specifically for preference management. electron-store is the most popular choice.
Definition: electron-store is a third-party package that securely manages JSON configuration files. It handles file corruption edge-cases, automatic parsing, and atomic writes.
Under the hood: "Atomic writes" mean the library writes the new settings to a temporary file first. Only when the temporary file is 100% complete and verified does it swap it with the actual settings file. This guarantees your settings never get corrupted during a crash.
Practical Implementation
First, install the package: npm install electron-store
// main.js
const Store = require('electron-store');
// Initialize the store. It automatically creates a 'config.json' in app.getPath('userData')
const store = new Store({
// You can define default values to prevent undefined errors
defaults: {
theme: 'system',
windowBounds: { width: 800, height: 600 },
isFirstLaunch: true
}
});
// Setting a value
store.set('theme', 'dark');
// Getting a value
const currentTheme = store.get('theme');
console.log(currentTheme); // 'dark'
// You can easily save nested objects using dot notation!
store.set('windowBounds.width', 1024);Funny Exaggeration: Writing your own JSON settings manager is a rite of passage for desktop developers, right up until a user force-restarts their computer during a write operation, wiping out their 500 custom keybinds. Just use electron-store.
4. Embedding Local Databases (SQLite/JSON Stores) 🗄️
The Problem
As your app grows, you might need to store thousands of records—like a list of 50,000 invoices or 10,000 chat messages.
If you use electron-store or standard JSON files for this, you have to load the entire file into memory just to read one invoice. If the JSON file grows to 100MB, your app will freeze every time it saves or reads data.
The Solution: Local SQLite Databases
You need a real database that can run locally on the user's machine without requiring them to install MySQL or PostgreSQL.
Definition: SQLite is a C-language library that implements a small, fast, self-contained, high-reliability SQL database engine. It stores the entire database in a single local file.
In the Node.js/Electron ecosystem, better-sqlite3 is the absolute industry standard. It is extremely fast because it is synchronous (meaning it doesn't suffer from Node's asynchronous event-loop overhead for tiny local database queries).
Practical Implementation
First, install it: npm install better-sqlite3. (Note: Because this is a native C++ module, Electron might require you to rebuild it for the specific Electron version using electron-rebuild, but let's look at the code).
// main.js
const { app } = require('electron');
const path = require('path');
const Database = require('better-sqlite3');
app.whenReady().then(() => {
// 1. Define where the database file should live
const dbPath = path.join(app.getPath('userData'), 'invoices.db');
// 2. Open (or create) the database
const db = new Database(dbPath);
// 3. Initialize your tables
db.exec(`
CREATE TABLE IF NOT EXISTS invoices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
client_name TEXT NOT NULL,
amount REAL NOT NULL,
date_created TEXT DEFAULT CURRENT_TIMESTAMP
)
`);
// 4. Create a prepared statement to insert data safely (prevents SQL injection)
const insertInvoice = db.prepare('INSERT INTO invoices (client_name, amount) VALUES (?, ?)');
// Insert a record
const info = insertInvoice.run('Acme Corp', 1500.50);
console.log(`Inserted invoice with ID: ${info.lastInsertRowid}`);
// 5. Query specific data without loading the whole database!
const getLargeInvoices = db.prepare('SELECT * FROM invoices WHERE amount > ?');
const largeInvoices = getLargeInvoices.all(1000); // Returns an array of objects
console.log(largeInvoices);
});Using SQLite, asking for 10 specific invoices out of 50,000 takes milliseconds and uses almost zero memory, keeping your Electron app blazing fast.
📚 References & Extra Reading
Keep these docs bookmarked. You will reference them constantly when building out file systems.
Challenge
You are building an Electron application that needs to persist user settings, such as a theme preference and window dimensions. Your task is to implement the complete Inter-Process Communication (IPC) flow for saving and loading these settings using the electron-store library, while adhering to security best practices with Context Isolation.
You will need to write the code for three separate files: main.js, preload.js, and renderer.js.
Requirements
1. main.js (Main Process):
- Import
ipcMainfromelectronandStorefromelectron-store. - Initialize a new
Storeinstance. - Create an IPC handler for the channel
'settings:save'. This handler should accept a settings object from the renderer and usestore.set()to persist it. - Create another IPC handler for the channel
'settings:load'. This handler should usestore.get()to retrieve the entire settings object and return it to the renderer.
2. preload.js (Preload Script):
- Import
contextBridgeandipcRendererfromelectron. - Use
contextBridge.exposeInMainWorldto securely expose an API object namedsettingsAPIto the renderer process. - The
settingsAPIobject must contain two asynchronous functions:save(settings): This function should invoke the'settings:save'channel, passing thesettingsobject to the main process.load(): This function should invoke the'settings:load'channel.
3. renderer.js (Renderer Process):
- Implement an asynchronous function named
saveUserSettings. - Inside this function, call the
window.settingsAPI.save()method exposed by the preload script. Pass it the following sample settings object:{ theme: 'dark', windowSize: { width: 1024, height: 768 } }. - Implement a second asynchronous function named
loadUserSettingsthat callswindow.settingsAPI.load()to retrieve the settings.
Expected result
Your solution should consist of three complete code blocks for main.js, preload.js, and renderer.js that fulfill all the requirements.
main.js
- Correctly imports
ipcMainfromelectronandStorefromelectron-store. - Creates a new
Storeinstance. - Implements
ipcMain.handle('settings:save', (event, settings) => { ... })which correctly callsstore.set(settings). - Implements
ipcMain.handle('settings:load', () => { ... })which correctly callsstore.get()on the entire object and returns the value.
preload.js
- Correctly imports
contextBridgeandipcRendererfromelectron. - Calls
contextBridge.exposeInMainWorldwith the key'settingsAPI'. - The exposed object contains
saveandloadasync functions that correctly callipcRenderer.invokewith the channels'settings:save'and'settings:load'respectively.
renderer.js
- Contains an async function
saveUserSettingsthat correctly callswindow.settingsAPI.save(...)with the specified settings object. - Contains an async function
loadUserSettingsthat correctly callswindow.settingsAPI.load().