Electron package - how to write/read files

半城伤御伤魂 提交于 2020-01-24 23:05:41

问题


I have file test.txt in my root directory of app. When I run my app with command npm start, I can write to my file without any problem, but when I make package using electron packager, writing text to my file is not possible anymore - I got error

Error: EACCES: permission denied, open './test.txt'

For this, I'm using node.js filesystem:

fs.writeFile("./test.txt",text,function(err){

    if(err) {
        return alert(err);
    }

    alert("saved");

});

How is possible to make this working? And is possible to include some extra folder in my app after package process? Thanks for your help!


回答1:


Didn't really found out what the problem was, so I tried another solution, which works for me (my main aim was to save data to some local memory of app).

I used npm package electron-store which is really easy to use.

You can get it by typing this to terminal

npm install electron-store

More info about it here: Electron store

Hope it helps someone else too :-)




回答2:


There are a lot of options to choose to package your electron app in 2019, so in case you come to this question like I did and are using electron-builder, please try my suggestion below.

If you are using electron-builder to package your application and need to read/write a file that is stored within your solution, you can add it to your files property in your package.json. The properties in this file property are files that are copied when packaging your electron app - reference.

In my example, I was reading/writing to file.json.

let fs = require("fs");

fs.writeFile("./file.json", "data to file", "utf-8", (error, data) => {
    if (error){
        console.error("error: " + error);
    }
});

My folder structure looked like this.

parent-folder
    app/
    assets/
    configs/
    images/
    resources/
    ...
    file.json

My app was not working after I packed it until I added the following file.json in my "build" property in my package.json.

"build": {
    "productName": "MyApp",
    "appId": "org.dev.MyApp",
    "files": [
        "app/dist/",
        "app/app.html",
        "app/main.prod.js",
        "app/main.prod.js.map",
        "package.json",
        "file.json", // << added this line
    ],
    //...
}


来源:https://stackoverflow.com/questions/46027816/electron-package-how-to-write-read-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!