FileSystemSyncAccessHandle: getSize() 方法
注意:此功能僅在 專用 Web Worker 中可用。
FileSystemSyncAccessHandle 介面的 getSize() 方法返回與該控制代碼關聯的檔案的位元組大小。
注意:在規範的早期版本中,close()、flush()、getSize() 和 truncate() 被錯誤地指定為非同步方法,並且一些瀏覽器的舊版本也是這樣實現的。然而,所有當前支援這些方法的瀏覽器都將它們實現為同步方法。
語法
js
getSize()
引數
無。
返回值
一個表示檔案大小(以位元組為單位)的數字。
異常
InvalidStateErrorDOMException-
如果關聯的訪問控制代碼已關閉,則會丟擲此錯誤。
示例
以下非同步事件處理函式包含在 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-getsize |
瀏覽器相容性
載入中…