Well, I'm working on a certain app that would improve work in the company. For this I would need to create, save and read a file without a dialog box.
I created this code with the help of documentation and the Internet:
const electron = require('electron');
let fs = require('fs'), app = electron.remote;
let localData, fileName = "appdata.json";
function loadAppData() {
fs.readFile(fileName, (err, data) => {
if (err) {
console.log("There was a problem reading the data!");
// console.log(err);
} else {
console.log("Data loaded!");
localData = JSON.parse(data);
console.log(localData);
}
});
}
function saveAppData(content) {
content = JSON.stringify(content);
fs.writeFile(fileName, content, (err) => {
if (err) {
console.log("There was a problem saving data!");
// console.log(err);
} else {
console.log("Data saved correctly!");
loadAppData();
}
});
}
function initappData() {
if (fs.existsSync(fileName)) {
console.log("File detected, loading");
loadAppData();
} else {
let defData = {
"patients": [],
"actions": [],
"visits": []
};
console.log("No file! I create! Saving! Loading!");
saveAppData(defData);
}
}
initappData();
And I have a problem because if the script works on the local version, after the application build on MacOS (using electron-builder) the error appears in the console: "There was a problem writing data!". After displaying the error content appears: Error: EROFS: read-only file system, open 'appdata.json'.
I checked permissions, I checked in other locations - still the same :( I was looking for a solution on the net but unfortunately nothing solved the problem.
Has anyone encountered such a problem?
After the build. The resource will be packaged inside asar
file
But this is just read-only
. You can't modify the file inside of asar
.
If I were you. I'm going to store the appData.json
at Application Support
. And I think this is the popular configure for application.
You can get the Application Data
path by using this.
function getAppDataPath() {
switch (process.platform) {
case "darwin": {
return path.join(process.env.HOME, "Library", "Application Support", "Your app name");
}
case "win32": {
return path.join(process.env.APPDATA, "Your app name");
}
case "linux": {
return path.join(process.env.HOME, ".Your app name");
}
default: {
console.log("Unsupported platform!");
process.exit(1);
}
}
}
function saveAppData(content) {
const appDatatDirPath = getAppDataPath();
// Create appDataDir if not exist
if (!fs.existsSync(appDatatDirPath)) {
fs.mkdirSync(appDatatDirPath);
}
const appDataFilePath = path.join(appDatatDirPath, 'appData.json');
content = JSON.stringify(content);
fs.writeFile(appDataFilePath, content, (err) => {
if (err) {
console.log("There was a problem saving data!");
// console.log(err);
} else {
console.log("Data saved correctly!");
loadAppData();
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With