FileSystemSyncAccessHandle: close() 方法
注意:此功能僅在 專用 Web Worker 中可用。
FileSystemSyncAccessHandle 介面的 close() 方法會關閉一個已開啟的同步檔案控制代碼,停用其上的一切後續操作,並釋放與該檔案控制代碼關聯的檔案上的獨佔鎖。
注意: 在規範的早期版本中,close()、flush()、getSize() 和 truncate() 被錯誤地指定為非同步方法,並且某些舊版瀏覽器也以這種方式實現了它們。然而,目前所有支援這些方法的瀏覽器都已將其實現為同步方法。
語法
js
close()
引數
無。
返回值
無(undefined)。
異常
無。
示例
以下非同步事件處理函式包含在 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-close |
瀏覽器相容性
載入中…