Lesson 3 of 28
javascriptFile System Access – Reading & Writing
10 mins
Course progress11%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 3 of 28
javascript10 mins
Keep these ideas in mind as you work through the lesson.
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);