node-webkit中使用sqlite3

sqlite3的官方文档提到:nodejs和node-webkit的ABI不同,所以通过npm install sqlite3下载的sqlite3是无法使用的,需要重新编译。

windows编译:以LTS版本(0.14.7)为例

一、所需编译环境

  1. 安装Python 2.7.14(不支持3.x版本)并设置好环境变量,下载地址:https://www.python.org/downloads/
  2. 安装最新的nodejs+npm 下载地址:https://nodejs.org/en/
  3. 安装VC++编译器VS2015,下载地址: http://download.microsoft.com/download/B/4/8/B4870509-05CB-447C-878F-2F80E4CB464C/vs2015.com_chs.iso(VS2015中有v140的工具集,编译sqlite3需要用到。安装时勾选相关C++模块,安装教程:https://jingyan.baidu.com/article/4dc40848e4709889d846f122.html,要安装很久,一般几个小时)

二、安装相关插件

通过cmd命令安装相关插件,最好用管理员权限启动cmd

  1. 安装windows-build-tools
    npm install --global --production windows-build-tools
  2. 安装node-gyp
    npm install -g node-gyp
  3. 安装nw-gyp

    npm install nw-gyp -g
  4. 安装node-pre-gyp
    npm install node-pre-gyp -g
  5. 在nw官网中(http://nwjs.net/doc/user/Advanced/Use-Native-Node-Modules.html)下载win_delay_load_hook.cc,然后替换node-gyp模块中的win_delay_load_hook.cc

    在 Windows, 在使用 node-gyp 或 npm安装原生模块之前,您需要用 这个文件 替换系统中的 <npm-path>\node_modules\node-gyp\src\win_delay_load_hook.cc,仅在您使用相同版本和架构的Node.js和nw.js.s才有效.
     

  6. 切换到你的项目路径,下载4.0.3版本sqlite3,本人用了最新版本5.0.0会编译出错
    npm install [email protected] --save

三、编译

切换到你项目中的sqlite3目录下,根据系统位数及node-webkit位数执行对应的命令

--target: node-webkit版本

--target_arch: node-webkit位数

--target_platform: 操作系统位数

  1. win32+64位
    node-pre-gyp rebuild --runtime=node-webkit --target=0.14.7 --target_arch=x64 --target_platform=win32

    生成的node_sqlite3.node文件在../sqlite3/lib/binding/node-webkit-v0.14.7-win32-x64目录中

  2. win32+32位

    node-pre-gyp rebuild --runtime=node-webkit --target=0.14.7 --target_arch=ia32 --target_platform=win32
  3. win64+64位

    node-pre-gyp rebuild --runtime=node-webkit --target=0.14.7 --target_arch=x64 --target_platform=win64
  4. win64+32位
    node-pre-gyp rebuild --runtime=node-webkit --target=0.14.7 --target_arch=ia32 --target_platform=win64

四、测试

打开node-webkit控制台,执行测试代码,运行成功!

测试代码如下:

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

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();

五、其他

在执行测试代码时,报了一个错误:

命令行cd到项目中的sqlite3目录下,执行命令安装node-pre-gyp即可

npm install node-pre-gyp

 

 

 

 

 

猜你喜欢

转载自blog.csdn.net/carfge/article/details/115230594