FileSystemSyncAccessHandle
注意:此功能僅在 專用 Web Worker 中可用。
FileSystemSyncAccessHandle 介面是 檔案系統 API 的一部分,代表檔案系統的同步訪問控制代碼。
此類僅在專用的 Web Worker 中可訪問(因此其方法不會阻塞主執行緒的執行),用於訪問 源私有檔案系統 中的檔案,這些檔案對終端使用者不可見。
因此,其方法不像使用者可見檔案系統中的方法那樣受到相同的安全檢查,效能也更優越。這使得它們適用於大規模的檔案更新,例如 SQLite 資料庫的修改。
該介面透過 FileSystemFileHandle.createSyncAccessHandle() 方法訪問。
注意: 在規範的早期版本中,close()、flush()、getSize() 和 truncate() 被錯誤地指定為非同步方法,並且一些舊版本的瀏覽器以這種方式實現它們。然而,所有支援這些方法的當前瀏覽器都將其實現為同步方法。
例項屬性
無。
例項方法
示例
以下非同步事件處理函式包含在 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 |
瀏覽器相容性
載入中…