Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron - How to add external files?

I have an Electron app. I try to make the app open an .exe file. I created a directory in the root folder named lib and placed the .exe file there. In development, I have no problem opening the file by using __dirname + '/lib/file.exe, but when I package the app (using yarn dist), it does not open the exe file and there is no lib folder anymore on the dist folder.

I tried writing to console the default location using console.log(__dirname) and it outputs \dist\win-unpacked\resources\app.asa (which is a file).

How can I add an external file that can be accessed when the app is packaged?

like image 579
user2298995 Avatar asked Sep 03 '17 10:09

user2298995


People also ask

How do you load an Electron file?

Add a file(s) to this Electron application using the “Drag and Drop” feature as well as by manually displaying the file explorer (system) dialog to select one or multiple files. Display system notification when a file(s) is added. On application relaunch, display the list of files.

How does Electron builder work?

electron-builder is a CLI tool that helps us create multi-platform distributions for Electron applications. It supports macOS, Windows, and Linux targets out of the box. It supports multiple file formats for each of these platforms such as dmg , pkg , mas and, mas-dev for macOS.


2 Answers

Managed to solve it by using extraResources. Should be declared under build in your package.json file.

For example:

  1. Create a new folder named extraResources adjacent to pacakge.json

  2. Add the following code to your package.json file:

    "build": {
        "extraResources": ["./extraResources/**"]
    }
    
  3. Then, you can access the files inside this folder by using __dirname + '/../extraResources/' from your main app.

like image 147
user2298995 Avatar answered Oct 19 '22 00:10

user2298995


Add the following code to package.json:

 "build": {
    "extraResources": [
      {
        "from": "./src/extraResources/",
        "to": "extraResources",
        "filter": [
          "**/*"
        ]
      }
    ]
  }

Then, you can access the files using

const configFile = path.join(path.dirname(__dirname), 'extraResources','config.json');

I use the following folders structure which allows me to run the app any way.

from project folder: node_modules\.bin\electron.cmd src\main\index.js

from unpacked source dist\win-unpacked\app.exe check-for-update

from installed folder C:\Users\user\AppData\Local\Programs\app\app.exe

+-- dist
|   +-- win-unpacked
|      +-- resources
|         +-- extraResources
|            config.json
+-- node_modules
+-- src 
|   +-- extraResources
|      config.json
|      someFile.js
|   +-- main
|      index.js
|   +-- render
|      index.js
like image 38
dimaqw Avatar answered Oct 18 '22 22:10

dimaqw