Monday, July 11, 2022

[SOLVED] Node: SerialPort is not a constructor

Issue

I'm trying to connect to my Raspberry pi's serialport via node but when i run the js file it comes up with this error:

data-console="true" data-babel="false">
    var serialport = new SerialPort("/dev/ttyAMA0", {
                 ^

TypeError: SerialPort is not a constructor
    at Object.<anonymous> (/home/pi/exploringrpi/chp13/xbee/nodejs/test.js:12:18)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3

node is at version 8.11.4 serialport is at version 7.0.2

This is the code:

// From the example code at www.npmjs.com/package/xbee-api
var util       = require('util');
var SerialPort = require('serialport').SerialPort;

var xbee_api   = require('xbee-api');
var C          = xbee_api.constants;

var xbeeAPI = new xbee_api.XBeeAPI({
  api_mode: 1
});

var serialport = new SerialPort("/dev/ttyAMA0", {
        baudRate: 115200});
serialport.on("open", function() {
  var frame_obj = {                 // AT Request to be sent to
    type: C.FRAME_TYPE.AT_COMMAND,  // Prepare for an AT command
    command: "NI",                  // Node identifer command
    commandParameter: [],           // No parameters needed
  };
  serialport.write(xbeeAPI.buildFrame(frame_obj));
});

// The data frames are outputted by this function
xbeeAPI.on("frame_object", function(frame) {
    console.log(">>", frame);
});

Hope you can help


Solution

You should probably remove the .SerialPort at the end of the require line:

var SerialPort = require('serialport').SerialPort;

The serial port documentation shows how it should be used, and it doesn't include that .SerialPort at the end:

var SerialPort = require('serialport');
var port = new SerialPort('/dev/ttyAMA0', {
  baudRate: /dev/ttyAMA0
});


Answered By - HugoTeixeira
Answer Checked By - Gilberto Lyons (WPSolving Admin)