简体   繁体   English

node.js serialport无法在SerialPort.list函数外部传递变量

[英]node.js serialport cannot pass variable outside SerialPort.list function

I am trying to get the COM port of my device at runtime using the node.js serialport module. 我正在尝试使用node.js serialport模块在运行时获取设备的COM端口

const SerialPort = require('serialport');
var fs = require('fs');

var serialVar = getSerialPort();

console.log("outer: "+serialVar);

function getSerialPort() 
{
    SerialPort.list(function (err, ports) {
        ports.forEach(function(port) {
            if (port.pnpId == "USB\\VID_0451&PID_BEF3&MI_00\\6&808E38E&0&0000") {
                console.log("inner: "+port.comName);
                return port.comName;
            } 
        });
    });
}

output: 输出:

outer: undefined
inner: COM8

From the output, it appears that getSerialPort() finishes after everything else in the script has run rather than running in it's entirety before continuing past the point it was called. 从输出中可以看出, getSerialPort()在脚本中的所有其他内容都已运行之后才完成,而不是在继续超过被调用点之前全部运行。 I'm not sure why this is. 我不确定为什么会这样。

I have tried several variations of this such as: 我已经尝试过几种变体,例如:

const SerialPort = require('serialport');
var fs = require('fs');

var serialVar = {};
getSerialPort();

console.log("outer: "+serialVar.port);
function getSerialPort() 
{
    SerialPort.list(function (err, ports) {
        ports.forEach(function(port) {
            if (port.pnpId == "USB\\VID_0451&PID_BEF3&MI_00\\6&808E38E&0&0000") {
                serialVar.port = port.comName;
                console.log("inner: "+serialVar.port);
            }
        });
    });
}

with no change. 没有变化。

Javascript is inherently asynchronous. JavaScript本质上是异步的。 What is happening is that the console.log is executing before the serial ports can be listed. 发生的情况是在列出串行端口之前, console.log正在执行。 The library provides a callback (which you are using) and a promise. 该库提供了一个回调(您正在使用)和一个Promise。 Either of these can be used to make sure things run in order. 这些中的任何一个都可以用来确保事情按顺序进行。 I recommend promises. 我推荐诺言。

 const SerialPort = require('serialport'); SerialPort.list() // returns promise that resolves to list of ports // filters for a specific port .then(ports => ports.filter(port => port.pnpId == "USB\\\\VID_0451&PID_BEF3&MI_00\\\\6&808E38E&0&0000")) // logs info .then(ports => {console.log('inner',port[0].comName, 'outer', port[0]); return ports}) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM