FileSystemObserver
非標準:此特性未標準化。我們不建議在生產環境中使用非標準特性,因為它們瀏覽器支援有限,並且可能會更改或被移除。但是,在沒有標準選項的特定情況下,它們可以是合適的替代方案。
FileSystemObserver 介面是 File System API 的一部分,它提供了一種機制來觀察使用者可訪問的檔案系統和 Origin Private File System (OPFS) 的變化。這意味著 Web 應用程式無需輪詢檔案系統即可查詢檔案或資料夾結構中的更改,從而避免了耗時且浪費資源的操作。
建構函式
FileSystemObserver()實驗性 非標準-
建立一個新的
FileSystemObserver物件例項。
例項方法
disconnect()實驗性 非標準-
停止觀察檔案系統。
observe()實驗性 非標準-
開始觀察指定檔案或目錄的變化。
示例
注意: 有關完整的可用示例,請檢視 File System Observer Demo(原始碼)。
初始化 FileSystemObserver
在開始觀察檔案或目錄更改之前,您需要初始化一個 FileSystemObserver 來處理觀察。這可以透過 FileSystemObserver() 建構函式完成,該建構函式接受一個回撥函式作為引數。
const observer = new FileSystemObserver(callback);
可以根據需要定義 回撥函式 的主體,以返回和處理檔案更改的觀察結果。
const callback = (records, observer) => {
for (const record of records) {
console.log("Change detected:", record);
const reportContent = `Change observed to ${record.changedHandle.kind} ${record.changedHandle.name}. Type: ${record.type}.`;
sendReport(reportContent); // Some kind of user-defined reporting function
}
observer.disconnect();
};
觀察檔案或目錄
一旦有了 FileSystemObserver 例項,您就可以透過呼叫 FileSystemObserver.observe() 方法來開始觀察檔案系統條目的更改。
透過將 FileSystemFileHandle 或 FileSystemDirectoryHandle 傳遞給 observe(),您可以觀察使用者可訪問的檔案系統或 Origin Private File System (OPFS) 中的檔案或目錄。例如,當使用 Window.showSaveFilePicker() 或 Window.showDirectoryPicker() 要求使用者選擇檔案或目錄時,可以返回這些物件的例項。
// Observe a file
async function observeFile() {
const fileHandle = await window.showSaveFilePicker();
await observer.observe(fileHandle);
}
// Observe a directory
async function observeDirectory() {
const directoryHandle = await window.showDirectoryPicker();
await observer.observe(directoryHandle);
}
您還可以透過將 FileSystemSyncAccessHandle 傳遞給 observe() 來觀察 OPFS 的更改。
// Observe an OPFS file system entry
async function observeOPFSFile() {
const root = await navigator.storage.getDirectory();
const draftHandle = await root.getFileHandle("draft.txt", { create: true });
const syncHandle = await draftHandle.createSyncAccessHandle();
await observer.observe(syncHandle);
}
停止觀察檔案系統
當您想停止觀察檔案系統條目的更改時,可以呼叫 FileSystemObserver.disconnect()。
observer.disconnect();
規範
目前不是規範的一部分。請參閱 https://github.com/whatwg/fs/pull/165 以獲取相關的規範 PR。
瀏覽器相容性
載入中…