WritableStream: phương thức getWriter()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since May 2022.

Note: This feature is available in Web Workers.

Phương thức getWriter() của giao diện WritableStream trả về một phiên bản mới của WritableStreamDefaultWriter và khóa luồng tới phiên bản đó. Trong khi luồng bị khóa, không thể lấy được trình ghi nào khác cho đến khi luồng này được phát hành.

Cú pháp

js
getWriter()

Parameters

None.

Return value

A WritableStreamDefaultWriter object instance.

Exceptions

TypeError

The stream you are trying to create a writer for is not a WritableStream or it is already locked to another writer.

Examples

The following example illustrates several features of this interface. It shows the creation of the WritableStream with a custom sink and an API-supplied queuing strategy. t then calls a function called sendMessage(), passing the newly created stream and a string. Inside this function it calls the stream's getWriter() method, which returns an instance of WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the string to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams.

js
const list = document.querySelector("ul");

function sendMessage(message, writableStream) {
  // defaultWriter is of type WritableStreamDefaultWriter
  const defaultWriter = writableStream.getWriter();
  const encoder = new TextEncoder();
  const encoded = encoder.encode(message);
  encoded.forEach((chunk) => {
    defaultWriter.ready
      .then(() => defaultWriter.write(chunk))
      .then(() => {
        console.log("Chunk written to sink.");
      })
      .catch((err) => {
        console.log("Chunk error:", err);
      });
  });
  // Call ready again to ensure that all chunks are written
  //   before closing the writer.
  defaultWriter.ready
    .then(() => {
      defaultWriter.close();
    })
    .then(() => {
      console.log("All chunks written");
    })
    .catch((err) => {
      console.log("Stream error:", err);
    });
}

const decoder = new TextDecoder("utf-8");
const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });
let result = "";
const writableStream = new WritableStream(
  {
    // Implement the sink
    write(chunk) {
      return new Promise((resolve, reject) => {
        const buffer = new ArrayBuffer(1);
        const view = new Uint8Array(buffer);
        view[0] = chunk;
        const decoded = decoder.decode(view, { stream: true });
        const listItem = document.createElement("li");
        listItem.textContent = `Chunk đã giải mã: ${decoded_`;
        list.appendChild(listItem);
        result += decoded;
        resolve();
      });
    },
    close() {
      const listItem = document.createElement("li");
      listItem.textContent = `[MESSAGE ĐÃ NHẬN] ${result`;
      list.appendChild(listItem);
    },
    abort(err) {
      console.log("Sink error:", err);
    },
  },
  queuingStrategy,
);

sendMessage("Hello, world.", writableStream);

Bạn có thể tìm thấy mã đầy đủ trong Ví dụ về người viết đơn giản của chúng tôi.

Thông số kỹ thuật

Thông số kỹ thuật
Streams
# ref-for-ws-get-writer①

Khả năng tương thích của trình duyệt