Search code examples
javascriptnode.jsnode-serialport

NodeJS serialport check if port exists function does not work


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!


Solution

  • 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"));
    })();