So I got this code to get the correct COM name:
//serialport lib import
var serialport = require("serialport");
//global var
var prt;
serialport.list(function (err, ports) {
ports.forEach(function (port) {
//this does NOT work.
prt = port.comName);
});
});
console.log(prt); //outputs UNDEFINED
The problem is that wherever I try to set prt to some value inside the .list()'s scope. It doesn't set the variable.
I can however call global functions. Which really doesn't make any sense to me.
//serialport lib import
var serialport = require("serialport");
//global var
var prt;
//global function
var printPort = function(port){
console.log(port);
}
serialport.list(function (err, ports) {
ports.forEach(function (port) {
//this does NOT work.
prt = port.comName);
//and this DOES
printPort(port.comName); //outputs "COMx"
});
});
I now that this is a scope related problem of course. I'm quite new to this, and quite confused about this behaviour. The fact that I can call the global function BUT I can't set the global variable doesn't make any sense to me.
Another last question would be how to make a function out of this that RETURNS the port name. Since it's async I can't return it.
Thank you very much.