如果要在electron中使用本机的串口硬件,需要用到node-serialport这个package。 由于electron集成的node runtime版本与本机存在差异,所以如果要在electron项目里引用serialport的话,必须要重新把它编译成此时electron使用的版本。
首先,新建一个electron项目文件夹(比如elec-proj),然后使用vscode 打开这个文件夹;
打开Terminal,npm初始化这个项目:
npm init接着,安装electron和serialport:
npm install electron --save-dev npm install serialport --save然后,安装electron-rebuild(用来重新编译serialport包):
npm install --save-dev electron-rebuild重新编译serialport包:
.\node_modules\.bin\electron-rebuild.cmd提示Rebuild Complete,表示编译完成。
接下来我们测试一下安装和编译是否成功:
新建main.js和index.html文件,分别拷贝官方例程到里面,然后添加串口模块,列出硬件串口设备。
//main.js const {app, BrowserWindow} = require('electron'); const SerialPort = require('serialport'); SerialPort.list().then( ports => ports.forEach(console.log), err => console.error(err) ); // 保持对window对象的全局引用,如果不这么做的话,当JavaScript对象被 // 垃圾回收的时候,window对象将会自动的关闭 let win; function createWindow(){ //创建浏览器窗口 win = new BrowserWindow({ width: 800, height: 600, webPreferences:{ nodeIntegration: true } }); //加载index.html文件 win.loadFile('index.html'); //打开开发者工具 win.webContents.openDevTools(); //当window被关闭,这个事件被触发 win.on('closed', () => { //取消引用的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 导入。 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World!</title> </head> <body> <h1>Hello World!</h1> We are using node <script>document.write(process.versions.node)</script>, Chrome <script>document.write(process.versions.chrome)</script>, and Electron <script>document.write(process.versions.electron)</script>. </body> </html>package.json文件:
{ "name": "electron-serialport", "version": "1.0.0", "description": "electron and serialport", "main": "main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "electron ." }, "author": "ykee", "license": "ISC", "devDependencies": { "electron": "^5.0.1", "electron-rebuild": "^1.8.4" }, "dependencies": { "serialport": "^7.1.5" } }启动:
npm start窗口:
控制台输出串口列表: