FileSystemSyncAccessHandle: write() 方法
注意:此功能僅在 專用 Web Worker 中可用。
FileSystemSyncAccessHandle 介面的 write() 方法會將指定緩衝區的內容寫入與該控制代碼關聯的檔案,可以選擇性地在給定偏移量處寫入。
位於 origin private file system 內的檔案對終端使用者不可見,因此不受使用者可見檔案系統中檔案執行的相同安全檢查的約束。因此,使用 FileSystemSyncAccessHandle.write() 執行的寫入操作效能更高。這使得它們適用於重要的、大規模的檔案更新,例如 SQLite 資料庫修改。
語法
js
write(buffer, options)
引數
buffer-
一個
ArrayBuffer或ArrayBufferView(例如DataView),表示要寫入檔案的緩衝區。 options可選-
一個包含以下屬性的選項物件
at-
一個數字,表示緩衝區應寫入檔案的起始位置的位元組偏移量。
返回值
一個數字,表示寫入檔案的位元組數。
異常
InvalidStateErrorDOMException-
如果關聯的訪問控制代碼已關閉,或者檔案的二進位制資料修改完全失敗,則會丟擲此異常。
QuotaExceededError-
如果增加的資料容量超出了瀏覽器的 儲存配額,則會丟擲此異常。
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-write |
瀏覽器相容性
載入中…