Search code examples
javascriptnode.jsnode-serialport

Serialport npm List of available COM ports


I'm having a problem with a part of my program and i think I know what the problem is I can't find way to fix it, hence need your help.

I think the problem is not with the serialport.list function but more with the way I am using it.

This is my code:

    var getPortsList= ()=>{
    var portsList = [];
    SerialPort.list((err, ports)=>{
      ports.forEach((ports)=>{
        portsList.push(ports.comName);
        //console.log(portsList);
      });
    });

    return portsList;

  };

So I wraped the list function in my own function and I am calling it when I need to check what ports are available. The problem I'm having is that I always get an empty array returned. If I console.log from inside the forEach i am definitely getting the COM port names and if I console.log from inside the list function after the forEach loop I'm getting the array and is not empty. I can only assume this is some issue relating to the concorrent nature of javascript, but I'm not quite sure how to solve this problem. I can see this is an important concept that will come up all the time and I would like to understand it a bit better. Any info on ways to handle this kind of issue or suitable links would be apreciated. Thank you. Best Regards Luis


Solution

  • I hope below solution will work for you.

    var getPortsList = (callback) => {
      var portsList = [];
    
      SerialPort.list((err, ports) => {
        ports.forEach((port) => {
          portsList.push(port.comName);
        });
    
        callback(null, portsList);
      });
    };
    

    The reason this does work is because the SerialPort.list method is asynchronous. This leaves your portsList empty because your SerialPort.list hasn't had a chance to complete and fill it yet. Adding in a completion callback gives it the time to run and provide you with a filled array of ports.