electron结合serialport插件开发硬件指令操作项目

别说谁变了你拦得住时间么 提交于 2020-04-19 15:34:50

    electron可以开发桌面系统,serialport包是node环境下连接串口设备的依赖,如果是用electron做硬件检测项目,需要考虑加入serialport包,但是我们直接npm install安装的serialport依赖,会因为binding的问题,在运行的时候报错,所以,一般会在下载安装依赖包之后,通过electron-rebuild再次编译,用来与electron匹配。

    这里通过实际操作来演示一个简单的入门demo。

    本实例需要一些准备环境,node10.20.0 版本,另外需要安装一个windows-build-tools,就是vc+python2.7的环境。有了这些环境,我们才能更方便的进行后续的操作。

    准备package.json

{
	"name": "electronserialport",
	"version": "0.0.1",
	"description": "",
	"main": "index.js",
	"author": "buejee",
	"license": "ISC",
	"scripts": {
		"dev": ".\\node_modules\\.bin\\electron ."
	},
	"dependencies": {
		"serialport": "^8.0.7"
	},
	"devDependencies": {
		"electron": "^2.0.4",
		"electron-rebuild": "^1.10.1"
	}
}

    electron主文件index.js

const {app,BrowserWindow,dialog} = require("electron")
const path = require("path")
const url = require("url")
let win;
app.on("ready",()=>{
	win = new BrowserWindow()
	win.on("close",()=>{
		win = null;
	})
	win.loadURL(url.format({
		pathname:path.join(__dirname,'index.html'),
		protocol:'file',
		slashes:true
	}))
	win.webContents.openDevTools();
})

app.on("window-all-closed",()=>{
	app.quit();
})

    串口测试模块文件serialportmodule.js

const Serialport = require("serialport");
Serialport.list().then((ports)=>{
	console.log(ports);
})

const $ = (id)=>{
	return document.getElementById(id);
}

let cnt = 0;
setInterval(()=>{
	$("count").textContent = cnt;
	cnt++;
},1000);

    主界面 index.html

<!doctype html>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>demo</title>
	</head>
	<body>
		<h2>hello,electron,serialport.</h2>
		<div id="count"></div>
	</body>
	<script>
		require("./serialportmodule.js");
	</script>
</html>

    以上文件准备好了,可以进入项目所在的目录下的命令行。

    1、npm install
    2、.\node_modules\.bin\electron-rebuild -f -w serialport
    3、 npm run dev

    以上第一步是安装依赖,包括项目依赖和运行依赖,第二部是对第一步中安装的serialport依赖做重新编译,因为默认运行会报错。第三步是进行启动项目的操作。具体会执行package.json文件中的scripts下的dev命令。

    最后,运行界面截图:

     

    控制台只是打印了一个空数组,因为电脑没有连接串口设备, 但是没有报错,证明electron与serialport结合是没有问题的。

发布了532 篇原创文章 · 获赞 288 · 访问量 148万+
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!