FileSystemSyncAccessHandle: flush() 方法

Baseline 已廣泛支援

此功能已成熟,並可在許多裝置和瀏覽器版本上執行。自 2023 年 3 月以來,它已在各種瀏覽器中可用。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

注意:此功能僅在 專用 Web Worker 中可用。

FileSystemSyncAccessHandle 介面的 flush() 方法會將透過 write() 方法對關聯檔案所做的任何更改持久化到磁碟。

請注意,只有當您需要在特定時間將更改提交到磁碟時,才需要呼叫此方法。否則,您可以讓底層作業系統在認為合適時處理此問題,這在大多數情況下應該是可以的。

注意: 在規範的早期版本中,close()flush()getSize()truncate() 被錯誤地指定為非同步方法,並且某些舊版本的瀏覽器也以這種方式實現它們。然而,所有當前支援這些方法的瀏覽器都將它們實現為同步方法。

語法

js
flush()

引數

無。

返回值

無(undefined)。

異常

InvalidStateError DOMException

如果關聯的訪問控制代碼已關閉,則會丟擲此錯誤。

示例

以下非同步事件處理函式包含在 Web Worker 中。在接收到主執行緒的訊息後,它會:

  • 建立一個同步檔案訪問控制代碼。
  • 獲取檔案大小並建立一個 ArrayBuffer 來儲存它。
  • 將檔案內容讀入緩衝區。
  • 對訊息進行編碼並將其寫入檔案末尾。
  • 將更改持久化到磁碟並關閉訪問控制代碼。
js
onmessage = async (e) => {
  // Retrieve message sent to work from main script
  const message = e.data;

  // Get handle to draft file
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // Get sync access handle
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // Get size of the file.
  const fileSize = accessHandle.getSize();
  // Read file content to a buffer.
  const buffer = new DataView(new ArrayBuffer(fileSize));
  const readBuffer = accessHandle.read(buffer, { at: 0 });

  // Write the message to the end of the file.
  const encoder = new TextEncoder();
  const encodedMessage = encoder.encode(message);
  const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });

  // Persist changes to disk.
  accessHandle.flush();

  // Always close FileSystemSyncAccessHandle if done.
  accessHandle.close();
};

規範

規範
檔案系統
# api-filesystemsyncaccesshandle-flush

瀏覽器相容性

另見