You can use the .close() method to instruct the serial port to close:

myserialport.close(function (err) {
    console.log('port closed', err);
});

.on('close') allows you to add the function as a listener of the 'close' event. But, it will simply wait for the event to occur (to be emitted) rather than instruct it to be done.

Answer from Jonathan Lonowski on Stack Overflow
🌐
Serialport
serialport.io › 📦 stream
📦 stream | Node SerialPort
November 8, 2024 - You can usually handle an error ... will cause the process to exit. Please refer to the node documentation for more details. The close event is emitted when the port is closed....
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › SerialPort › close
SerialPort: close() method - Web APIs | MDN
1 month ago - close() closes the serial port if previously-locked SerialPort.readable and SerialPort.writable members are unlocked, meaning the releaseLock() methods have been called for their respective reader and writer.
Top answer
1 of 3
2

As you can see in /node_modules/serialport/lib/serialport.js: close-event may not be emitted (unlike disconnect).

You can add console.log locally like below to simple debug.

P.S. I tested it on Win7x32. Close-event is emitted.

SerialPort.prototype._disconnected = function(err) {
  this.paused = true;
  this.emit('disconnect', err);

  // add: console.log('1', this.closing);

  if (this.closing) {
    return;
  }

  // add: console.log('2', this.fd);

  if (this.fd === null) {
    return;
  }

  this.closing = true;
  if (process.platform !== 'win32') {
    this.readable = false;
    this.serialPoller.close();
  }

  // add: console.log('3');

  SerialPortBinding.close(this.fd, function(err) {
    // add: console.log('4', this._events.close.toString());

    this.closing = false;
    if (err) {
      debug('Disconnect close completed with error: ', err);
    }
    this.fd = null;
    this.emit('close'); // it's your target
  }.bind(this));
};

Reconnect example

var SerialPort = require('serialport');
var port = new SerialPort('COM1', {autoOpen: false, baudRate: 9600});

function open () {
    port.open(functon (err) {
        if (!err)
           return;

        console.log('Port is not open: ' + err.message);
        setTimeout(open, 10000); // next attempt to open after 10s
    });
}

port.on('open', function() {
    function send() {
        if (!port.isOpen()) // v5.x require
            return console.log('Port closed. Data is not sent.');

        port.write(123, function (err) {
            if (err)
                console.log('Error on write: ' +  err.message)

            port.drain(() => console.log('DONE'));
        });
    }

    setInterval(send, 1000);
});

port.on('close', function () {
    console.log('CLOSE');
    open(); // reopen 
});

port.on('data', (data) => console.log('Data: ' + data));
port.on('error', (err) => console.error('Error: ', err.message));

open(); // open manually
2 of 3
1

According to the serialport.io,

The resume() method causes an explicitly paused, Readable stream to resume emitting 'data' events, switching the stream into flowing mode.

Simply, when port is closes, serialport library emits a close event

serialport.on('close', function(error){
  if(error.disconnected === true){
    console.log("disconnected");
 }
} 

, which will allow us whether port is disconnected or not.

That means the disconnected port is not available to re-establish the connection again, so you have to use serialport.resume() method to re-enable the connection.

serialport.on('close', function(err){
  console.log("Port closed.");
  if(err.disconnected === true){
    console.log("Disconnected!");
    serialport.resume(function(e){
      reconnectDevice(); // Serial Port Initialization Function. It's your method to declare serial port.
      console.log("Error on resuming port:", e);
    });
  }
});

After that, it will automatically switch COM ports and you won't get error as 'Port Access denied.'.

🌐
GitHub
github.com › serialport › node-serialport › issues › 2043
No close event emitted when a device is physically removed for an open port. · Issue #2043 · serialport/node-serialport
March 4, 2020 - What should have happened? The close event shall be emitted when the physical device is disconnected, without delay and without the need to write to the port. It's no longer visible in the system, verified with ls -l /dev/tty.* It shall work ...
Author   serialport
🌐
Npmdoc
npmdoc.github.io › node-npmdoc-serialport › build › apidoc.html
Node.js package to access serial ports. Welcome your ...
... ... **Example** Writes `data` and waits until it has finish transmitting to the target serial port before calling the callback. ``` function writeAndDrain (data, callback) { sp.write(data, function () { sp.drain(callback); }); } ``` ### .close (callback) Closes an open connection.
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
GitHub
github.com › serialport › node-serialport › issues › 1480
'serialport' close event is not working properly · Issue #1480 · serialport/node-serialport
February 14, 2018 - Simple NodeJS application with open, close, error and data event functions is enough to reproduce the issue. ... serialport.on("open", showPortOpen); serialport.on("data", initData); serialport.on("close", showPortClose); serialport.on("error", ...
Author   serialport
Find elsewhere
🌐
YouTube
youtube.com › hey delphi
NodeJS : SerialPort 'close' event never fire - YouTube
NodeJS : SerialPort 'close' event never fireTo Access My Live Chat Page, On Google, Search for "hows tech developer connect"So here is a secret hidden featur...
Published   May 8, 2023
Views   5
🌐
GitHub
github.com › serialport › node-serialport › issues › 1450
How to reset a serialport connection · Issue #1450 · serialport/node-serialport
January 23, 2018 - If I kill my process and restart the process the device will connect again and the app will receive data but again stop after 19 minutes. instead of trying to kill the process and restart I am trying to just close the serialport connection and start a new connection.
Author   serialport
🌐
GitHub
github.com › serialport › node-serialport › issues › 1897
Close Port after readline parser ends · Issue #1897 · serialport/node-serialport
July 3, 2019 - The code executes, and I get the returned data, but after receiving I want to close the port and not use a persistent connection. const cl = console.log; const SerialPort = require('serialport') const Readline = require('@serialport/parser-readline'); const port = new SerialPort('/dev/tty.SLAB_USBtoUART', { baudRate: 115200 }); const parser = new Readline(); //const parser = port.pipe(new Readline({ delimiter: '\r\n' })) port.pipe(parser); parser.on('data', function(line){ console.log(`> ${line}`); }) parser.on('finish', function(){ port.close(); cl('closed'); }) port.write("something \r\n");
Author   serialport
🌐
GitHub
github.com › serialport › node-serialport › issues › 388
Attempting to close a serial port that had the "error" event raised results in 'Aborted' message and terminates Node · Issue #388 · serialport/node-serialport
September 28, 2014 - However, after that, I wish to perform a reconnect.. so I attempt to close() the port. The text "Aborted." is written to the terminal and then the NodeJS instance dies, with no chance of recovery.
Author   serialport
🌐
npm
npmjs.com › package › serialport-v5
serialport-v5 - npm
August 2, 2017 - The close event's callback is called with no arguments when the port is closed. In the case of a disconnect it will be called with a Disconnect Error object (err.disconnected == true).
      » npm install serialport-v5
    
Published   Aug 02, 2017
Version   5.0.0
Author   Chris Williams
🌐
Lightrun
lightrun.com › answers › serialport-node-serialport-consider-end-even-in-addition-to-close-on-serialportstream
Consider "end" even in addition to "close" on @serialport/stream
From https://github.com/node-serialport/node-serialport/issues/1688#issuecomment-426316689 it might be worth adding the end event to the stream. We would do it to work well with other streams. ... Worked in #1926 thinking it will be an option to enable or disable this behavior. If we have it on by default we need a HUGE warning in the changelog. ... Consider "end" even in addition to "close...
🌐
GitHub
github.com › serialport › node-serialport › issues › 15
SerialPort.close() throws error · Issue #15 · serialport/node-serialport
July 14, 2011 - When calling SerialPort.close() an error is thrown in serialport.js on line 98: TypeError: Object [object Object] has no method 'close' 98 line is: this.readStream.close(); but readable streams do not have close() method, only destroy().
Author   serialport
🌐
Stack Overflow
stackoverflow.com › questions › 39229995 › node-close-arduino-serialport-connection-before-doing-anything
node.js - node close Arduino serialport connection before doing anything - Stack Overflow
var SerialPort= require("serialport"); SerialPort.list(function(err,ports){ ports.forEach(function(port){ console.log(port.comName); console.log(port.manufacturer); }); }); var port= new SerialPort("/dev/cu.usbmodem641",{ baudRate: 9600, parser: SerialPort.parsers.readline('n') }); port.on('open',function(){ console.log('opened'); }); port.on('close',function(){ console.log('closed'); }); port.on('data',function(data){ console.log(data); }); port.on('error',function(error){ console.log("Errore: "+error); }); console.log(":-)"); I run sudo node script.js while Arduino has Serial.println(1);
🌐
Serialport
serialport.io › serialport usage
SerialPort Usage | Node SerialPort
November 8, 2024 - You can use this if you've disabled the autoOpen option or have previously closed an open port. const { SerialPort } = require('serialport') const port = new SerialPort({ path: '/dev/tty-usbserial1', baudRate: 57600 }) port.write('main screen turn on', function(err) { if (err) { return ...
🌐
GitHub
github.com › serialport › node-serialport › issues › 150
Buggy `close()` routine - Node "hangs" · Issue #150 · serialport/node-serialport
In addition, Node will hang even after close() is called. ... var SerialPort = require("SerialPort").SerialPort; var port = new SerialPort("/dev/ttySerial0", { "baudRate": 57600 }); port.on("open", function() { console.log("open", arguments); ...
Author   serialport