在 Electron 中使用 SQLite3

11,892 阅读3分钟
原文链接: github.com

最近项目需要做一个简单的客户端,客户端需要保存各种数据,以便用户离线也能继续使用,当有网的时候再进行数据同步,所以这就需要客户端自带数据库的功能。

作为一个不会 C/C++ 的前端,在构建客户端的工具上肯定是选择 Electron 了,没有用 NW.js 的原因很简单,社区没有 Electron 大。

数据库方面,SQL 系的嵌入式数据库只有 SQLite 了,毕竟这么多年的老字号,经得住考验,比较靠谱。但是 Node 版的 SQLite 并不是纯 JavaScript 写的,而是原生 Node 模块,即包含 C/C++ 代码。

工具齐全,就差集成安装了,其它都挺顺利,但是在安装 SQLite 这一步,真的是让人吐血,从官网到百度里的各种方法试了个遍,但总会出现各种让你看不懂的错误,直到最后,还是得靠谷歌。

不BB了,直接写操作步骤:

1. 新建项目

看你心情,随便找个地方创建一个项目,其实就是个文件夹,然后执行:

npm init

结构目录如下:

sqlite-electron/
  ├── package.json
  ├── index.js
  ├── server.js
  └── index.html

2. 安装 Electron

npm install  electron -D

3. 安装 windows 下的相关环境

npm install --global --production windows-build-tools

详情参考 On Windows

4. 安装 node-gyp

npm install -g node-gyp

5. 构建 SQLite

npm install sqlite3 --build-from-source --runtime=electron --target=2.0.7 --dist-url=https://atom.io/download/electron

--target 参数的值是你安装的 electron 的版本

6. 安装 express

这个跟 SQLite 无关,是用来验证我们能否进行相关操作。

npm install express

7. 验证结果

我懒得写代码,直接从这些库的文档里拷贝代码:

// index.js


const {app, BrowserWindow} = require('electron')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow() {
    // 创建浏览器窗口。
    win = new BrowserWindow({width: 800, height: 600})

    // 然后加载应用的 index.html。
    win.loadFile('index.html')

    // 打开开发者工具
    win.webContents.openDevTools()

    // 当 window 被关闭,这个事件会被触发。
    win.on('closed', () => {
        // 取消引用 window 对象,如果你的应用支持多窗口的话,
        // 通常会把多个 window 对象存放在一个数组里面,
        // 与此同时,你应该删除相应的元素。
        win = null
    })
}

// Electron 会在初始化后并准备
// 创建浏览器窗口时,调用这个函数。
// 部分 API 在 ready 事件触发后才能使用。
app.on('ready', createWindow)

// 当全部窗口关闭时退出。
app.on('window-all-closed', () => {
    // 在 macOS 上,除非用户用 Cmd + Q 确定地退出,
    // 否则绝大部分应用及其菜单栏会保持激活。
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // 在macOS上,当单击dock图标并且没有其他窗口打开时,
    // 通常在应用程序中重新创建一个窗口。
    if (win === null) {
        createWindow()
    }
})

// 在这个文件中,你可以续写应用剩下主进程代码。
// 也可以拆分成几个文件,然后用 require 导入。
// server.js


var express = require('express')
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
var app = express()

// 这段代码用来测试 SQLite
db.serialize(function() {
  db.run("CREATE TABLE lorem (info TEXT)");

  var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
  for (var i = 0; i < 10; i++) {
      stmt.run("Ipsum " + i);
  }
  stmt.finalize();

  db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
      console.log(row.id + ": " + row.info);
  });
});

db.close();


// 这段代码用来测试 server 创建是否成功
app.get('/test', function(req, res) {
    res.json({
        code: 0
    })
})

var btn = document.getElementById('btn')
btn.onclick = function() {
    var server = app.listen(3000, function() {
        var host = server.address().address
        var port = server.address().port

        console.log('Example app listening at http://%s:%s', host, port)
    })
}
<!DOCTYPE html>
  <html>
    <head>
      <meta charset="UTF-8">
      <title>Hello Electron!</title>
    </head>
    <body>
      <h1>Hello Electron!</h1>
      <button id="btn">开启服务器</button>

      <script src="./server.js"></script>
    </body>
  </html>

package.json 中加入一条启动命令

"scripts": {
        "start": "electron ."
}

8. 见证奇迹

命令行中执行:

npm start

image

弹出了我们的应用程序!

点击 开启服务器 按钮:

image

成功打印启动 server 的信息!

在浏览器中输入 URL:

http://localhost:3000/test

image

成功返回数据!

9. 结尾

到这里我们的整个应用已经完成了,麻雀虽小,但五脏俱全。
打包应用我就不在这里写了,照着文档去弄就好了,目前一切顺利,并没有发现什么坑。
溜了~