FileSystemSyncAccessHandle: read() 方法
注意:此功能僅在 專用 Web Worker 中可用。
read() 方法是 FileSystemSyncAccessHandle 介面的一個方法,它將與控制代碼關聯的檔案的內容讀取到指定的緩衝區中,可以選擇性地在給定偏移量處讀取。
語法
js
read(buffer, options)
引數
buffer-
一個
ArrayBuffer或ArrayBufferView(例如DataView),它表示檔案內容將被讀取到的緩衝區。請注意,您不能直接操作ArrayBuffer的內容。而是建立一個型別化陣列物件,如Int8Array或DataView物件,該物件以特定格式表示緩衝區,並使用它來讀取和寫入緩衝區的內��。 options可選-
一個包含以下屬性的選項物件
at-
一個數字,表示應從中讀取檔案的位元組偏移量。
返回值
一個數字,表示從檔案中讀取的位元組數。
異常
InvalidStateErrorDOMException-
如果關聯的訪問控制代碼已關閉,則會丟擲此錯誤。
TypeError-
如果底層檔案系統不支援從指定檔案偏移量讀取檔案,則會丟擲此錯誤。
示例
以下非同步事件處理函式包含在 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();
};
注意: 在規範的早期版本中,close()、flush()、getSize() 和 truncate() 被錯誤地指定為非同步方法,並且一些舊版本的瀏覽器以這種方式實現它們。然而,所有支援這些方法的當前瀏覽器都將其實現為同步方法。
規範
| 規範 |
|---|
| 檔案系統 # api-filesystemsyncaccesshandle-read |
瀏覽器相容性
載入中…