cant send data to serialport using node.js

25 views Asked by At

i want to send data to serialport so i can read it from arduino and do stuff, but when i am trying to send data to serial port i am getting different kinds of errors, like path is not defined or serialport is not a constructor. i need simple code that sends data to serial port. anyone know how to do that? this is my code:

const express = require('express');
const { SerialPort } = require('serialport');

const app = express();
const port = 3000;

app.use(express.json());

const portName = 'COM3'; // Change this to match your serial port
const baudRate = 115200;

const serialPort = new SerialPort(portName, { baudRate: baudRate });

app.post('/send', (req, res) => {
    const { message } = req.body;
    serialPort.write(message);
    res.send('Message sent to serial port');
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

this is error i get:

PS C:\Users\User\Desktop\Startup\Startup Web> node .\server.js
C:\Users\User\Desktop\Startup\Startup Web\node_modules\@serialport\stream\dist\index.js:57
            throw new TypeError(`"path" is not defined: ${settings.path}`);
            ^

TypeError: "path" is not defined: undefined
    at new SerialPortStream (C:\Users\User\Desktop\Startup\Startup Web\node_modules\@serialport\stream\dist\index.js:57:19)
    at new SerialPort (C:\Users\User\Desktop\Startup\Startup Web\node_modules\serialport\dist\serialport.js:15:9)
    at Object.<anonymous> (C:\Users\User\Desktop\Startup\Startup Web\server.js:12:20)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
    at node:internal/main/run_main_module:28:49

Node.js v20.11.1

i want to send data to serialport but i just cant seem to do that

1

There are 1 answers

0
Lajos Arpad On

You will need to specify your portName as path:

const serialPort = new SerialPort({ path: portName, baudRate: baudRate });