NodeJS serialport check if port exists function does not work

3k views Asked by At

I have built a Function that check if Port exists via array given from SerialPort package.

The port is connected. And when I run the code outside the function it's work(true while port's plugged). When i tried to run it inside a function I recive undefined

function exists(portName) {
    SerialPort.list(function (err, ports) {
        ports.forEach(function (port) {
            console.log(port.comName);
            if (port.comName == portName) {
                return true
            }
        });
    });
}
console.log(exists('COM7'));

results:

NodeJS service has started.
undefined
COM1
COM7
Port is connected.

Full code at: https://github.com/eshk12/SerialPort-HTTP-Server/blob/master/routes/index.js

Thanks!

2

There are 2 answers

6
Jonas Wilms On BEST ANSWER

As port checking is asynchronous you probably need a promising function:

 function exists(portName) {
  return new Promise(res => {
    SerialPort.list((err, ports)=>{
        res(ports.some(port => port.comName === portName));
   });
 });
}

Or as @skirtle noted it can be even shorter:

const exists = portName => SerialPort.list().then(ports => ports.some(port => port.comName === portName ));

So you can do:

 exists("CM7").then(res => console.log(res?"exists":"doesnt exist"));

Or:

(async function(){

   console.log(await exists("CM7"));
})();
0
skirtle On

The line return true is returning from the anonymous function you've passed to forEach, not from your exist method.

SerialPort.list appears to be asynchronous so you're going to have to use callbacks, promises, etc. rather than relying on returning a value directly from exist.