Search code examples
node.jsnode-serialport

SerialPort.list is not a function


I tried to create an array of port, to which serial devices are connected using the serialport module of nodeJS. I used the following code, which should in theory work I think:

var getPortsList = (callback) => {
    var portsList = [];

    SerialPort.list((err, ports) => {
        ports.forEach((port) => {
            portsList.push(port.comName);
        });

        callback(null, portsList);
    });
};

Whenever I execute it tho, I get the following error: TypeError: SerialPort.list is not a function. U tried to google the problem, but could not find anything useful. Help in any way is greatly appreciated.


Solution

  • The way you import serialport changed in version >= 10:

    Below you have two equivalent examples to import serialport module.

    Solution #1

    var sp = require('serialport')
    
    sp.SerialPort.list()
    .then((data) => console.log(data))
    .catch(err => console.log(err));
    

    Solution #2

    const {SerialPort} = require('serialport')
    
    SerialPort.list()
    .then((data) => console.log(data))
    .catch(err => console.log(err));
    

    For reference, it's stated here: https://serialport.io/docs/guide-upgrade#exports