Ubuntu16.04下安装electron和sqlite3

xiaoxiao2021-07-04  295

 

环境:

Ubuntu 16.04

Node.js 8.12.0

Npm 6.4.1

Cnpm 6.0.0

Electron 3.0.0

 

1、安装node.js和electron

首先安装nodejs,新版的nodejs是自带npm的。

  sudo apt-get install curl

  curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -

  sudo apt-get install -y nodejs

然后全局安装cnpm,cnpm是用国内淘宝的一个源,用法和npm是一样的,只需要将npm改成cnpm就可以了,建议使用cnpm,能避免一些未知的问题。

  sudo npm install -g cnpm --registry=https://registry.npm.taobao.org

全局安装electron,electron就不多介绍了。

sudo cnpm install -g electron

2、获取官方案例

从git上获取一个官方给出的一个例子。一般一个electron工程就是一个文件夹,文件夹中最基本的就是三个文件。Package.json配置文件,main.js主进程文件,index.html主界面。具体的可以参照electron中文文档。文件夹中还会有一个node_modules的文件夹,里面存放着工程的依赖库。按着如下步骤就可以运行第一个程序了。

git clone https://github.com/electron/electron-quick-start

cd electron-quick-start

cnpm install

(根据配置文件package.json里面的以来信息安装依赖,node_modules文件夹可以删除,然后执行这条命令就是了,用过node.js的应该知道)

   cnpm start

(electron是支持脚本执行的,脚本写在package.json文件里面的scripts部分,这条命令就是执行的脚本语句,相当于electron .)

3、安装sqlite3

有一点申明,node.js的库分为全局安装和本地安装,全局安装只能用于命令行,不能用于工程引用,因此工程想要引用的依赖库,需要在工程文件夹下进行本地安装。全局安装添加-g。

安装node-gyp,用于编译安装c和c++的依赖库。

npm install -g -save node-gyp

安装sqlite3并保存到package.json里面。

cnpm install --save sqlite3

安装依赖。

cd node_modules/sqlite3

cnpm install

查看安装的库所在文件夹的名称,我的是node-v57-linux-x64,因此下面的命令里面就写这个名字。

ls lib/binding/

node-gyp configure --module_name=node_sqlite3 --module_path=../lib/binding/node-v57-linux-x64

重编译sqlite3的库,下面的target的值是electron的版本号,electron的版本号在package.jason文件里面可以看到。

node-gyp rebuild --target=3.0.0 --arch=x64 --target_platform=linux --dist-url=https://atom.io/download/atom-shell --module_name=node_sqlite3 --module_path=../lib/binding/node-v57-linux-x64

将sqlite3的库所在文件夹名称进行修改。不然找不到库。

mv lib/binding/node-v57-linux-x64/ lib/binding/electron-v3.0-linux-x64/

 

4、sqlite3使用

连接数据库。Database的括号里面放置的是数据库文件的全路径,也可以放置一个数据库的名字,详细的就不多讲了。

var sqlite3 = require('sqlite3').verbose(); const path = require('path'); var db = new sqlite3.Database(path.join(__dirname, 'database.db'));

数据库初始化建表。

db.serialize(function() { db.run("CREATE TABLE IF NOT EXISTS tablename (info TEXT)"); });

数据的插入。

db.run("INSERT INTO tablename(info,info2) VALUES ($d1,$d2)",{$d1:"f1",$d2:"f2"},function(err,res){ console.log(err,res,this.lastID); });

数据的删除。

db.run("delete from tablename where rowid > 1",function(err,res){ console.log(err,res,this.changes,this.lastID); });

数据更新。

db.run("UPDATE tablename SET info = ? WHERE rowid = ?", [ "bar", 2 ]);

数据的查询。

db.get("select * from tablename where rowid=?",[1],function(err,res){ console.log(err,res); });  

转载请注明原文地址: https://www.6miu.com/read-4821259.html

最新回复(0)