Can't find file when using fs.readFileSync from packaged electron app


#1

I use sqlite in my application. When running the application from source (electron ./) I have no trouble reading the file:

const fileBuffer = fs.readFileSync('data/db.sqlite');

Which I then pass to sql.js.

However after packaging using electron-packager, this line of code throws the error:

Uncaught Error: ENOENT: no such file or directory, open 'data/db.sqlite'

I thought it might have to do with the relative location of the file. As a (very crude) test I copied the db.sqlite file to every directory from the root of the packaged app to the sql.js node_module. This did not help.

I can’t seem to figure out the behavior of the ‘fs’ module in this context: what is the starting path when calling readFileSync(). I expected it to be the directory of the file containing the code. Which in my case would be in ‘resources/app/dist/build.js’ relative to the packaged electron executable.

My sqlite db is at ‘resources/app/data/sqlite.db’. So I tried ‘…/data/sqlite.js’, which didn’t work. Also tried ‘resources/app/data/sqlite.db’ thinking the start might be the location of the executable.

I was hoping someone could point me in the right direction here.

edit:

Fixed by using process


#2

the ‘data’ floder was supposed to be at the same directory where ‘electron.exe’ is.


#3

I put the db.sqlite file in the same directory as my packaged electron application executable. Is this equal to the same directory as electron.exe?


#4

You was expected to put the db floder in the same diretory as your packaged executable not only the db.sqlite file, isn’t it?


#5

Not exactly. The problem was that I didn’t know how to get the absolute path to the application, from within the application.

When calling fs.readFileSync('db.sqlite') it tries to read the file relative from the root of the filesystem, in my case: '/'. I’m not sure what it will do on windows. Maybe the root of the hard drive.

__dirname also returned the root of the file system. So I couldn’t do `${__dirname}/db.sqlite`.

I needed some variable that described the absolute path to somewhere in the vicinity of the packaged executable.

In the GitHub issue the poster describes that Electron has patched the process object with a property: process.resourcesPath. This gives the absolute path to the ‘resources’ folder that is included in the packaged app.

This finally allowed me to get the path to the data folder: `${process.resourcesPath}/data/db.sqlite`.