Electron子进程开启Koa微服务

写在前面的话

项目结构

image-20200629144253807

1、配置 Server 打包位置

1
2
3
4
5
6
7
8
9
10
// vue.config.js
pluginOptions: {
electronBuilder: {
builderOptions: {
//...
// 匹配server中的所有文件夹和文件
extraResources: ['server/**/**'] // 指定打包 Server 到 Resource 文件夹中。
}
}
}

会将 server 文件夹打包到 Resources 文件夹中。为什么不打包大 app.asar 中呢?因为.asar 文件是只读的,无法进行数据库的写入。

2、配置webpack

1
2
3
4
// vue.config.js
configureWebpack: {
externals: ['pg', 'sqlite3', 'tedious', 'pg-hstore']
}

3、创建 Electron 子进程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function createServerProcess() {
if (!isDevelopment) {
// 生产环境
serverProcess = fork('../server/index.js', [], {
cwd: path.join(__dirname, '../server')
})
} else {
// 开发环境
serverProcess = fork(require.resolve('../server/index.js'))
serverProcess.on('close', code => {
console.log('子线程已经退出', code)
})
}
}

程序退出时,需要终止子进程 process.kill(serverProcess.pid)

至此:Mac可以启动服务和访问数据库

问题

windows 下无法启动服务 && Please install sqlite3 错误

  1. 在 Sequelize 中指定数据库的类型,默认有时无法读取到。

  2. 执行 cnpm i 命令安装依赖包,会自动对sqlite3进行编译,node_module/sqlite3/lib/binding 中可以看到文件。或者执行命令 npm run postinstall(管理员身份执行,npm i 会默认执行该命令)

  3. 或者手动编译 npm rebuild 进行手动编译。

  4. 执行命令编译为 electron匹配的 sqlite3 文件。

1
node-gyp rebuild --target=6.1.0 --arch=x64 --target_platform=win32 --dist-url=https://npm.taobao.org/mirrors/node/ --module_name=node_sqlite3 --module_path=../lib/binding/electron-v6.1-win32-x64
  1. target 为 electron 版本
  2. –arch 架构;–traget_platform: 目标系统
  3. –dist-url: Header 文件下载地址

注:参考另一篇文中:Koa使用Sqlite3和Sequelize