Skip to content

Instantly share code, notes, and snippets.

@tsuriga
Last active April 23, 2024 10:18
Show Gist options
  • Save tsuriga/2aeedf9579bc55037519 to your computer and use it in GitHub Desktop.
Save tsuriga/2aeedf9579bc55037519 to your computer and use it in GitHub Desktop.
Saving and loading files in an Electron application
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tsuri's Electron Note Sample App</title>
<link href="./app.css" rel="stylesheet" />
<script src="app.js"></script>
</head>
<body>
<h1>Welcome to note sample app!</h1>
<p>Here you can read and write notes that are saved on your computer</p>
<textarea id="note"></textarea>
<hr/>
<input type="button" id="save" value="Save note" />
<input type="button" id="load" value="Load note" />
</body>
</html>
'use strict';
const fs = require('fs'),
remote = require('remote'),
dialog = remote.require('dialog');
document.addEventListener('DOMContentLoaded', function() {
var btnLoad = document.getElementById('load'),
btnSave = document.getElementById('save'),
note = document.getElementById('note');
btnLoad.addEventListener('click', function () {
dialog.showOpenDialog(function (filePaths) {
if (filePaths === undefined) {
return;
}
var filePath = filePaths[0];
try {
note.value = fs.readFileSync(filePath, 'utf-8');
console.log('Loaded file:' + filePath)
} catch (err) {
console.log('Error reading the file: ' + JSON.stringify(err));
}
});
});
btnSave.addEventListener('click', function () {
dialog.showSaveDialog(function (filePath) {
if (filePath === undefined) {
return;
}
fs.writeFile(filePath, note.value, function (err) {
if (err === undefined) {
dialog.showMessageBox({
message: 'The file has been saved!',
buttons: ['OK']
});
} else {
dialog.showErrorBox('File save error', err.message);
}
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment