在 electron+vite+vue3+express 项目中使用better-sqlite3

一、安装 electron-rebuild 和 better-sqlite3

yarn add -D electron-rebuild
yarn add better-sqlite3

Electron 内置的 Node.js 版本和编译到 better-sqlite3 的 Node.js 版本不同将可能导致安装失败,所以此处需要安装 electron-rebuild 重建 Node.js 模块。(注意安装顺序,否则可能出现安装失败的问题)

二、使用 electron-rebuild 重建 Node.js 模块

如果安装完 better-sqlite3 不重建直接运行,则可能出现以下报错:

Error: The module 'xxx'
was compiled against a different Node.js version using
NODE_MODULE_VERSION xxx. This version of Node.js requires
NODE_MODULE_VERSION xxx. Please try re-compiling or re-installing
the module (for instance, using `npm rebuild` or `npm install`).

修改 package.json 文件中的 scripts 内容:

  "scripts": {
    "dev": "vite",
    ...
    "rebuild": "electron-rebuild -f -w better-sqlite3"
  },

执行命令:yarn run rebuild 重建 Node.js 版本。

三、better-sqlite3 的基本使用

新建 db/DBManager.ts 文件:

const sqliteDB = require('better-sqlite3');
const path = require('path');

const dbPath = 
    process.env.NODE_ENV === "development" ? 
    "./wallpapers.db" : path.join(process.resourcesPath, "./wallpapers.db")

// 打开数据库,如果不存在则创建,cacheSize 缓存数据最大值
const db = new sqliteDB(dbPath,{ cacheSize: 15 });
db.pragma('journal_mode = WAL');

exports.db = db;

新建 db/ImageManager.ts 文件:

const dbmgr = require("./DBManager.ts");
const db = dbmgr.db;

// 读取信息
const readAllImgs = () => {
    try {
        const result = db.prepare("SELECT * FROM imgs", { cached: true }).all();
        return result;
    } catch (error) {
        console.error(error);
        throw error;
    }
};

// 批量插入数据 (values 是一个对象)
const insertWallhaven = (keys, values) => {
    try {
        // 使用命名参数 例: $id、$url ... ; 数据 values => [{id: xx, url: xx},{}]
        // 由于插入的数据 id 可能重复,所以此处使用 OR IGNORE
        const insertQuery = db.prepare(
            `INSERT OR IGNORE INTO wallhaven (${keys.join(",")}) VALUES (${keys.map((item) => "$" + item).join(",")})`
        );
        const insertMany = db.transaction((values) => {
            for (const val of values) {
                insertQuery.run(val)
            }
        });
        insertMany(values);
    } catch (error) {
        console.error(error);
        throw error;
    }
};

module.exports = {
    readWallhaven,
    insertWallhaven,
};

四、打包

修改 electron-builder.json5 文件,添加打包配置:

  "directories": {
    ...
  },
  // 添加数据库文件
  "extraResources": [
    "./wallpapers.db"
  ],

将数据库文件放在根目录下:

将数据库文件放在根目录下


说明: 后续在使用过程中发现,每次安装新的第三方库时都需要重新执行 yarn run rebuild 命令重建 Node.js 模块,否则可能出现报错。

五、参考资料

  • 19
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
在浏览器环境使用 Node.js 的 fs 模块是不被允许的。因此,如果使用 Electron + Vite + Vue 开发应用程序,需要使用 Electron 提供的 API 来进行文件系统操作。 在 Electron ,可以使用 Node.js 的 fs 模块,因为 Electron 应用程序是基于 Chromium 和 Node.js 构建的。如果需要在 Vue 使用 Electron 的 fs 模块,可以通过 Vue 的插件机制来实现。 首先,在 Electron 主进程添加一个模块来暴露 fs 对象: ```javascript // main.js const { app, BrowserWindow } = require('electron') const fs = require('fs') let mainWindow = null function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: false, }, }) mainWindow.loadFile('index.html') mainWindow.on('closed', function () { mainWindow = null }) // 将 fs 模块暴露给 Vue 实例 mainWindow.fs = fs } app.on('ready', createWindow) app.on('window-all-closed', function () { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', function () { if (mainWindow === null) { createWindow() } }) ``` 然后,在 Vue 的插件使用 fs 对象: ```javascript // fs-plugin.js export default { install: (Vue) => { Vue.prototype.$fs = window.require('electron').remote.getCurrentWindow().fs }, } ``` 最后,在 Vue 应用程序使用插件即可: ```javascript // main.js import Vue from 'vue' import App from './App.vue' import fsPlugin from './plugins/fs-plugin' Vue.use(fsPlugin) new Vue({ render: (h) => h(App), }).$mount('#app') ``` 在 Vue 组件,可以像这样使用 $fs 对象: ```javascript this.$fs.readFile('/path/to/file', (err, data) => { if (err) throw err console.log(data) }) ``` 需要注意的是,读取本地文件需要应用程序有相应的权限,可以在 package.json 文件添加以下配置来获取权限: ```json { "name": "my-app", "version": "0.1.0", "main": "main.js", "scripts": { "start": "electron .", "postinstall": "electron-builder install-app-deps" }, "build": { "appId": "com.example.myapp", "productName": "My App", "directories": { "output": "dist_electron" }, "files": [ "dist/**/*", "main.js", "package.json" ], "extraResources": [ { "from": "assets", "to": "assets" } ], "dmg": { "contents": [ { "x": 110, "y": 150 }, { "x": 480, "y": 150, "type": "link", "path": "/Applications" } ] }, "mac": { "category": "public.app-category.developer-tools", "icon": "assets/icon.icns" }, "win": { "target": [ "nsis", "msi" ], "icon": "assets/icon.ico" }, "linux": { "category": "Development", "icon": "assets/icon.png" } }, "dependencies": { "electron": "^13.1.1" }, "devDependencies": { "@vue/cli-plugin-babel": "^4.5.0", "@vue/cli-plugin-eslint": "^4.5.0", "@vue/cli-service": "^4.5.0", "babel-eslint": "^10.1.0", "electron-builder": "^22.11.7", "eslint": "^6.7.2", "eslint-plugin-vue": "^6.2.2", "vue-template-compiler": "^2.6.11" }, "buildResources": "public" } ``` 在 package.json 文件添加了 "buildResources": "public" 配置,表示将 public 目录下的文件打包到应用程序。如果需要读取 public 目录下的文件,可以使用相对路径来访问。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值