2

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!

Itzik.B
  • 1,023
  • 2
  • 15
  • 35

2 Answers2

5

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"));
})();
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    `SerialPort.list` also returns a `Promise` so you could chain that rather than creating a new one directly. – skirtle Sep 10 '17 at 09:28
  • I'm really can't understand how does it work. i'm trying to make it as `if syntax` same as the code i published, all i have succssed to do with that is `console.logged` it – Itzik.B Sep 10 '17 at 12:47
  • @itzkb https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Jonas Wilms Sep 10 '17 at 12:51
  • ```function exists(portName) { return new Promise(res => { SerialPort.list((err, ports)=>{ PortResults(ports.some(port => port.comName === portName)); }); }); } function PortResults(res){ return res; } console.log(exists(portName));``` I have checked the linked and i tried with the following explainations as you can see. and I recive `Promise { }` – Itzik.B Sep 10 '17 at 13:29
  • @itzikb your code doesnt make sense. Cant you just take over mys? – Jonas Wilms Sep 10 '17 at 13:32
  • it is your code, i would like to use a function that return true/false accordding to the port com's status. for example `isActive() -> true/false` i want to run this function from multiple places and I didnt understand the meaning of all this. – Itzik.B Sep 10 '17 at 14:06
0

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.

skirtle
  • 27,868
  • 4
  • 42
  • 57