5

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

enter image description here

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.

enter image description here

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.

4

2 回答 2

8

运行时.exe,当前目录可能不同,因此相对路径将不正确。正如您发现的那样,您需要将完整路径放在一起,而不是process.resourcesPath您应该使用app.getAppPath().

let dbFile = path.join(app.getAppPath(), 'app', 'db', 'example.db')

这应该是数据库文件的正确路径。您可能面临的另一个问题是,.exe通常将使用Asar格式打包,该格式提供读取访问权限但不提供写入访问权限。因此,如果您需要写入数据库,最好将其放在其他地方。electron.app.getPath(name) API提供了许多路径,例如,您可以使用它app.getPath("userData")来获取为每个用户应用程序数据提供的路径。在这种情况下,您的应用程序必须在该位置创建数据库文件。

于 2017-03-21T14:19:00.410 回答
0

我做了几次尝试,唯一对我有用的是用数据库文件替换app.asar文件,即

const { app } = window.require('electron').remote;
const appPath = app.getAppPath().replace("app.asar", "db_name.sqlite");
于 2019-11-17T13:14:06.140 回答