Reputation: 827
When running my Electron project normally, like electron ./artist-test-kit-main.js
, everything works fine. When I build the project into an executable, attempts to load files start failing, like: Uncaught Error: ENOENT: no such file or directory, open 'asset-editor\data.json'
So I ran a test to see if there's a difference in the root directory between the normal (electron ./artist-test-kit-main.js
) execution and the .exe's.
Within index.js
(launched by index.html
, launched by artist-test-kit-main.js
which is a standard electron.js initiator file):
console.log(fs.readdirSync('./'))
In the .exe
, this outputs:
In the normal dev execution (electron ./artist-test-kit-main.js
), this outputs:
This usual root directory of the project is, after being packaged, stored in the resources
directory seen in the .exe
execution root directory. So now all my file reads seem to be broken because of this discrepancy in root directories.
How can I solve this?
My package.json
shows the build arguments used:
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "artist-test-kit-main.js",
"dependencies": {
...
},
"scripts": {
"start": "electron .",
"start-artist": "electron ./artist-test-kit-main.js",
"build": "electron-packager ./ game --platform=win32 --arch=x64 --overwrite=true",
"build-art": "electron-packager ./ asset-editor --platform=win32 --arch=x64 --overwrite=true"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"electron-packager": "^15.4.0"
}
}
Upvotes: 2
Views: 894
Reputation: 3527
Use __dirname
instead of .
.
refers to the current working directory (cwd), which is the directory in which the node process was started.
For an unpackaged app, this is usually the root folder of your project, producing the expected results. For a packaged app, the cwd will likely be where the Electron executable is stored. The app's contents (what was previously the root folder) are put inside resources/app
or resources/app.asar
relative to the executable.
The way to unify the packaged and unpackaged scenarios is to use __dirname
, which contains the directory of the currently running Node script. This way, it will be the same as using .
in an unpackaged app, but will return the path with resources/app
in the packaged scenario, as that is then the location of the currently running Node script.
This is why you'll often see people using something like `file://${__dirname}/assets/index.html`
to address files in Electron.
If you use require('./file.js')
, the path is evaluated relative to the location of the calling script and will work as if you had used __dirname
.
Upvotes: 2