print serialport's listener every 5 results with nodejs

559 views Asked by At

I have a device that connected to the computer via usb cable. I have access to the data with nodejs via SerialPort module.

I Want to get the data online but I want to take data each for each 5 instances. here is the code and GIT: https://github.com/eshk12/SerialPort-HTTP-Server/blob/master/routes/index.js

in the first run he print the 5th instance and reset the variable count but doesn't proceed again to 5th:

Here is the console:

serialport>npm run start

> [email protected] start D:/serialport
> node ./bin/www

init start
1else
2else
3else
4else
5main
GET /hey 200 652.150 ms - 12
1else
2else
3else
4else

parser.on('data', render); - this listener keep sending data everytime

1

There are 1 answers

0
Itzik.B On

I have fixed the issue, I have take out the serialport dependecies from the router and let it run permantly and push the data into variable lastresult once some1 access to router localhost:3000/hey he will print the results.

var express = require('express');
var router = express.Router();
var cors = require('cors');
var SerialPort = require('serialport');
router.use(cors());

console.log('init start');
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort('COM7');
const parser = new Readline();
port.pipe(parser);
var count = 0;
var lastresult = '';
function counter(data){
  if(++count == 5){
    lastresult = data;
    count = 0;
  }
}
parser.on('data', counter);
router.get('/hey', function (req, res) {
  res.send(lastresult);
});
module.exports = router;