StorageManager: getDirectory() 方法

Baseline 已廣泛支援

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

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

注意:此功能在 Web Workers 中可用。

getDirectory() 方法是 StorageManager 介面的一個方法,用於獲取一個 FileSystemDirectoryHandle 物件引用,該物件允許訪問儲存在 源私有檔案系統 (OPFS) 中的目錄及其內容。

語法

js
getDirectory()

引數

無。

返回值

一個 Promise,它會解析為一個 FileSystemDirectoryHandle 物件。

異常

SecurityError DOMException

如果瀏覽器無法將請求的目錄對映到本地 OPFS,例如由於儲存或記憶體限制,則會丟擲此錯誤。在某些瀏覽器中,如果 getDirectory() 在隱私瀏覽模式下被呼叫,也會丟擲此錯誤。

UnknownError DOMException

在某些瀏覽器中,如果 getDirectory() 在隱私瀏覽模式下被呼叫,則會丟擲此錯誤。

示例

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

  1. 使用 getDirectory() 獲取一個代表 OPFS 根目錄的 FileSystemDirectoryHandle,並將其儲存在 root 變數中。
  2. 使用 FileSystemDirectoryHandle.getFileHandle() 獲取一個檔案控制代碼。
  3. 使用 FileSystemFileHandle.createSyncAccessHandle() 建立一個同步檔案訪問控制代碼。
  4. 獲取檔案大小並建立一個 ArrayBuffer 來儲存它。
  5. 對檔案進行讀寫。
  6. 將更改持久化到磁碟並關閉同步訪問控制代碼。
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();
};

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

規範

規範
檔案系統
# dom-storagemanager-getdirectory

瀏覽器相容性

另見