Node.js串行端口访问被拒绝

问题描述

我正在尝试使用以下代码通过node.js中的serialport发送字符串:

function createSerialPort() {
  myPort = new SerialPort('COM3',{
    baudrate: 115200,dataBits: 8,parity: 'none',stopBits: 1,flowControl: 0
  })
  myPort.write("135");
}

每次运行它都会给我这个错误

(node:8468) UnhandledPromiseRejectionWarning: Error: opening COM3: Access denied
(node:8468) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:8468) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.js process with a non-zero exit code

我到处都在寻找解决方法(我是使用Serialport的新手),而我发现的唯一解决方案就是这样做:

function createSerialPort() {
  myPort = new SerialPort('COM3',flowControl: 0
  },true)
  myPort.write("135");
}

然后该解决方案给了我这个

(node:18192) UnhandledPromiseRejectionWarning: TypeError: callback.call is not a function
    at SerialPort._error (C:\examplepath\node_modules\@serialport\stream\lib\index.js:198:14)
    at C:\examplepath\node_modules\@serialport\stream\lib\index.js:242:12
(node:18192) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:18192) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

解决方法

形成串行端口文件(V9.x.x)

功能 port.write 应该获得回调作为第二个参数 例如

port.write('main screen turn on',function(err) {
  if (err) {
    return console.log('Error on write: ',err.message)
  }
  console.log('message written')
})

将代码更改为:

function createSerialPort() {
  myPort = new SerialPort('COM3',{
    baudRate: 115200,dataBits: 8,parity: 'none',stopBits: 1,flowControl: 0
  },true)
  myPort.write("135",err.message)
  }
  console.log('message written')
})
}