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
May 19, 2026 - 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.'.

🌐
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.
🌐
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
🌐
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 › 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
Find elsewhere
🌐
GitHub
github.com › serialport › node-serialport › issues › 1340
RE-Establish connection to port after closed. · Issue #1340 · serialport/node-serialport
September 19, 2017 - Hello, Accordding to my last question close event never fire. I was unabled to detected if the COM is disconnected so I have created my own way to detect it. I have created timestamp, and checked it with interval() every 1 sec to see if is connected. when it's detect the COM is unplugged I have try to re-establish the connection be re-instance port with SerialPort like you'll see inside the code below.
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
🌐
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
🌐
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
🌐
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
🌐
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 ...
🌐
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);
🌐
GitHub
github.com › serialport › node-serialport › issues › 458
Close and Disconnect events doesn't work properly · Issue #458 · serialport/node-serialport
February 9, 2015 - When I gets unplugged a device, I cannot find a way to detect this. There is no automatic event...nothing! I know that it's an old bug (#393) but I've tryed with Windows 8.1 and Windows 7 and I've always had the same response namely no e...
Author   serialport
🌐
GitHub
github.com › serialport › node-serialport › issues › 638
Calling `close()` removes all event listeners (including "error") · Issue #638 · serialport/node-serialport
December 1, 2015 - When a SerialPort is closed by calling close(), all event listeners are removed (as per the documentation). This behavior might be undesired. If one calls write on a closed serial port connection without passing a callback to the write m...
Author   serialport
🌐
GitHub
github.com › serialport › node-serialport › issues › 2776
Hanging promise after close() in flowing mode · Issue #2776 · serialport/node-serialport
April 11, 2024 - Wait a few seconds, then close the SerialPort instance: serialport.close(...). (Adding pause() or destroy() produces the same result) ... Even after calling close() or destroy(), the promise created on unix-read.ts:41 never resolves / rejects. As a result, Node.js is prevented from exiting indefinitely.
Author   serialport
🌐
npm
npmjs.com › package › serialport › v › 5.0.0-beta8
Node Serialport
July 17, 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
    
Published   Aug 29, 2023
Version   5.0.0-beta8
Author   Chris Williams