Lesson 3 of 28 · javascript
File System Access – Reading & Writing
Duration: 10 mins
File System Access – Reading & Writing
Electron provides app.getPath(name) to locate OS‑specific folders (userData, desktop, documents).
const { app } = require('electron');
const dataPath = app.getPath('userData');
Read a file (async):
const fs = require('fs').promises;
async function loadNotes(){
const file = path.join(dataPath, 'notes.json');
try {
const raw = await fs.readFile(file, 'utf-8');
return JSON.parse(raw);
} catch(e){
return [];
}
}
Write a file:
async function saveNotes(notes){
const file = path.join(dataPath, 'notes.json');
await fs.writeFile(file, JSON.stringify(notes, null, 2), 'utf-8');
}
Show a dialog before overwriting:
const { dialog } = require('electron');
const { response } = await dialog.showMessageBox({
type: 'question',
buttons: ['Cancel', 'Overwrite'],
defaultId: 1,
title: 'Confirm',
message: 'Overwrite existing file?'
});
if (response === 1) await saveNotes(notes);