Background:
In my app, I have a local DB file, named example.db
which is read by the main.js
. The project structure and part of my main.js
program is shown below.
Project folder architecture
main.js
const {
app,
BrowserWindow,
dialog,
Menu
} = require('electron')
const fs = require('fs')
const path = require('path')
const sqlite3 = require('sqlite3').verbose()
// load dataBase
let dbFile = 'app/db/example.db'
const db = new sqlite3.Database(dbFile)
Package.json
{
"name": "Example",
"version": "1.0.0",
"description": "",
"main": "./app/main.js",
"scripts": {
"postinstall": "install-app-deps",
"start": "electron ."
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"electron-builder": "^15.5.1",
"electron-prebuilt": "^1.4",
"electron-rebuild": "^1.5.7",
"electron-packager": "^8.1.0"
},
"dependencies": {
"jquery": "^3.1.1",
"sqlite3": "^3.1.8"
}
}
Problems:
I can load the DB file successfully by running the npm start
, however, after I successfully packing my program to Windows platform by running the following command line under Example
folder:
node_modules/.bin/electron-packager --platform=win32 --arch=x64 .
I ran the .exe
file, but the system shows that it can not find my Database file.
Tried methods:
I tried to modify the db filepath in the main.js
by using process.resourscesPath
as the following:
// load dataBase
let dbFile = path.join(process.resourcesPath, '/app/db/example.db')
const db = new sqlite3.Database(dbFile)
However, after doing that, I neither can load the DB file from running .exe
, nor can I make it by running npm start
.
Question:
I want to what is the proper way to store my Database file, and how to write the path of it in my back-end program (main.js
in this example). Thanks.
When running the .exe
, the current directory might be different so the relative path will not be correct. As you figured out you need to put together a full path, but rather than process.resourcesPath
you should use app.getAppPath()
.
let dbFile = path.join(app.getAppPath(), 'app', 'db', 'example.db')
This should be give the correct path to the database file. An additional problem you may face is that the .exe
will typically be packaged with the Asar format, which gives read access but not write access. So if you need to write to the database, it may be better to place it elsewhere. There are a number of paths provided by the electron.app.getPath(name) API, so for example you could use app.getPath("userData")
to get the path provided for per-user application data. In this case your application would have to create the database file at that location.
来源:https://stackoverflow.com/questions/42900015/electron-packager-can-not-locate-local-db-file-after-packing