Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include a folder and the files inside it to electron build using electron-builder?

I have a few JSON files inside a directory named data in the working directory of my Electron project. I succeeded in building the app using electron-build with the following configuration (package.json).

{
  "name": "My App",
  "version": "0.0.9",
  "description": "TEST DESC",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "pack": "build --dir",
    "dist": "build"
  }
  "author": "Test",
  "license": "CC0-1.0",
  "build": {
    "appId": "test.tester.test",
    "directories": {
      "app": ""
    },
    "extraFiles": [
      "data"
    ],
    "dmg": {
      "contents": [
        {
          "x": 110,
          "y": 150
        },
        {
          "x": 240,
          "y": 150,
          "type": "link",
          "path": "/Applications"
        }
      ]
    },
    "win": {
      "target": "squirrel",
      "icon": "build/icon.ico"
    }
  },
  "devDependencies": {
    "electron": "~1.7.8",
    "electron-builder": "^20.11.1"
  },
  "dependencies": {
    "electron-settings": "^3.1.4",
    "jquery": "^3.3.1",
    "leveldown": "^3.0.0",
    "mkdirp": "^0.5.1",
    "shelljs": "^0.8.1"
  }
}

I suppose the data directory is not getting added to the build file. Because I am using the files inside of the data directory to render the views in the app, which is not working in the built app. Please suggest a solution.

I am using these JSON files inside the app like this:

fs.readFile('./data/userdata.json', 'utf8', function readFileCallback(err, data) {      
    if(data == '') { data = '[]'; }
    var users = JSON.parse(data);

    //Render Code
});
like image 275
Abhijith C S Avatar asked May 05 '18 20:05

Abhijith C S


1 Answers

"build": {
    "extraResources": [
        {
            "from": "data",
            "to": "data"
        }
    ]
}

After add like this then Electron-builder will copy the data folder to app's resource/data after packing the app. So that you can read the files with this.

const dataPath =
  process.env.NODE_ENV === 'development'
    ? path.join(__dirname, '../../data')
    : path.join(process.resourcesPath, 'data');

fs.readFile(path.join(dataPath,'userdata.json', 'utf8', function readFileCallback(err, data) {      
  if(data == '') { data = '[]'; }
  var users = JSON.parse(data);

  //Render Code
});
like image 192
tpikachu Avatar answered Oct 15 '22 16:10

tpikachu