Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. SerialPort
  4. close()

SerialPort: close() method

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Secure context: This feature is available only insecure contexts (HTTPS), in some or allsupporting browsers.

Experimental:This is anexperimental technology
Check theBrowser compatibility table carefully before using this in production.

Note: This feature is available inDedicated Web Workers.

TheSerialPort.close() method of theSerialPort interface returns aPromise that resolves when the port closes.

Syntax

js
close()

Parameters

None.

Return value

APromise.

Description

close() closes the serial port if previously-lockedSerialPort.readable andSerialPort.writable members are unlocked, meaning thereleaseLock() methods have been called for their respective reader and writer.

However, when continuously reading data from a serial device using a loop, the associatedreadable stream will always be locked until thereader encounters an error. In this case, callingreader.cancel() will forcereader.read() to resolve immediately with{ value: undefined, done: true } allowing the loop to callreader.releaseLock().

js
// Without transform streams.let keepReading = true;let reader;async function readUntilClosed() {  while (port.readable && keepReading) {    reader = port.readable.getReader();    try {      while (true) {        const { value, done } = await reader.read();        if (done) {          // reader.cancel() has been called.          break;        }        // value is a Uint8Array.        console.log(value);      }    } catch (error) {      // Handle error...    } finally {      // Allow the serial port to be closed later.      reader.releaseLock();    }  }  await port.close();}const closedPromise = readUntilClosed();document.querySelector("button").addEventListener("click", async () => {  // User clicked a button to close the serial port.  keepReading = false;  // Force reader.read() to resolve immediately and subsequently  // call reader.releaseLock() in the loop example above.  reader.cancel();  await closedPromise;});

Closing a serial port is more complicated when usingtransform streams. SeeClose a serial port for guidance.

Specifications

Specification
Web Serial API
# dom-serialport-close

Browser compatibility

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp