I'm using nodeJS's SerialPort Package for connecting to computer ports.
About Package's close event here.
I have created this code, I would like to know why close/disconnect event never fire when I disconnect the COM
const express = require('express');
const router = express.Router();
//
const cors = require('cors');
router.use(cors());
//
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort('COM7',function (err) {
    if (err) {
        return console.log('Error: ', err.message);
    }
});
const parser = port.pipe(new Readline());
/*
var lastresult = '';
var count = 0;
*/
port.on('open', function() {
    console.log('~Port is open.');
    parser.on('data', console.log);
});
port.on('disconnect', function () {
    console.log('disconnected');
});
port.on('close', function () {
    console.log('closed');
});
router.get('/', function (req, res) {
    res.send('index');
});
module.exports = router;
I'm trying to think if I use it wrong because I havn't saw example for using this event.
Thanks for the help :)
I have created timestamp every time I recive data from the COM,
And check it with interval() every time.
setInterval(function () {
    if (Date.now() - lastDataTime > 1000 || !comStatus) {
        comStatus = false;
        port.close();
        port = new SerialPort(comPort, function (err) {
            if (err) {
                error = 'Error: ' + err.message;
                return console.log(error);
            }
        });
    }
}, 1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With