安装
首先在装好Electron的项目中安装SerialPort:
npm install serialport
使用
然后在main.js中尝试使用:
const SerialPort = require('serialport');
const port = new SerialPort('COM1', {
autoOpen: true}, (err) => {
if (err) {
return console.log(err.message);
}
});
port.on('open', function () {
port.write('main screen turn on', function (err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
});
基本会出现第一个错误,nodejs版本错误:
解决方案:
1.安装
npm install --save-dev electron-rebuild
安装完后修改package.json的scripts,添加:
"scripts": {
"install": "electron-rebuild"
}
然后运行
npm run install
然后等待他重新构建完毕:
再次运行npm start:
程序正常运行,打印出了:
另一个错误
如果在你使用npm run install的时候出现了类似这个错误:
gyp ERR! find VS
gyp ERR! find VS msvs_version not set from command line or npm config
gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
gyp ERR! find VS could not use PowerShell to find Visual Studio 2017 or newer
gyp ERR! find VS looking for Visual Studio 2015
gyp ERR! find VS - not found
gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
gyp ERR! find VS
gyp ERR! find VS **************************************************************
gyp ERR! find VS You need to install the latest version of Visual Studio
gyp ERR! find VS including the "Desktop development with C++" workload.
gyp ERR! find VS For more information consult the documentation at:
gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
gyp ERR! find VS **************************************************************
gyp ERR! find VS
这说明:
- 你的VS没有安装
- 你的C++工具集没有装全
解决方案:
- 使用vs官方下载器Visual Studuio Installer安装Visual Studio 2017
- 安装下图工具集
工具集:
然后重启重试。