來源私人檔案系統提供已針對效能高度最佳化的特殊檔案,例如可為檔案內容提供就地且專屬的寫入權限。開發人員可以呼叫 createSyncAccessHandle()
來存取這類檔案,這是在 FileSystemFileHandle
物件上公開的方法。這個呼叫會產生 FileSystemSyncAccessHandle
。
FileSystemSyncAccessHandle
是檔案基本功能,可為本機檔案提供高效能的存取權。其中一項主要用途是將 C/C++ 程式碼移植到 Wasm;不過,Wasm 尚未完全支援非同步呼叫,因此使用 Asyncify 程式庫做為替代方案,效能會大幅降低。讓 FileSystemSyncAccessHandle
的所有方法都符合與 POSIX 類似的同步檔案 API,以 Wasm 為基礎的應用程式預期。讓 API 更符合人體工學,同時大幅提升效能。
新功能
FileSystemSyncAccessHandle
會公開下列非同步方法,但自 Chromium 108 起同步。
truncate(newSize)
:將與存取控制代碼相關聯的檔案重新調整為newSize
個位元組。如果newSize
大於目前檔案大小,則會對檔案加上空值位元組,否則會截斷檔案。getSize()
:傳回與存取控制代碼相關聯的檔案大小,以位元組為單位。flush()
:確保與存取控制代碼相關聯的檔案內容包含透過write()
完成的所有修改。close()
:清除存取控點,然後關閉。關閉存取控點將停用其他所有作業,並在與存取控制代碼相關聯的項目上放開鎖定。
// In a `Worker`:
const root = await navigator.storage.getDirectory();
const fileHandle = await root.getFileHandle('test', { create: true });
// `createSyncAccessHandle()` is still async.
const accessHandle = await fileHandle.createSyncAccessHandle();
// Both `read()` and `write()` were sync before.
accessHandle.read(/* ... */);
accessHandle.write(/* ... */);
// New: synchronous as of Chromium 108.
console.log(accessHandle.getSize());
accessHandle.truncate(123);
accessHandle.flush();
accessHandle.close();
我需要做些什麼?
請注意,將方法從非同步改為同步是網站公開的變更,可能會發生中斷。雖然在同步方法中使用 await
不需要人工管理,但使用 Promise.then()
的所有功能都會無法運作。如果您將任何先前非同步與現在同步方法的結果鏈結至 then()
呼叫,則需要變更程式碼。
// (✅) This won't break, but you better remove the superfluous `await`:
await accessHandle.flush();
// ✅ Correct:
accessHandle.flush();
// ⛔️ This will break, and you need to restructure your code:
accessHandle.flush().then(/* Follow-up code */);
// ✅ Correct:
accessHandle.flush();
/* Follow-up code */
相關連結
- TAG 審查
- 規格
- 規格問題 (導致變更)
- ChromeStatus 項目
- Chromium 錯誤