FileSystemObserver

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

非标准:此特性未标准化。我们不建议在生产环境中使用非标准特性,因为它们浏览器支持有限,并且可能会更改或被移除。但是,在没有标准选项的特定情况下,它们可以是合适的替代方案。

FileSystemObserver 接口是 File System API 的一部分,它提供了一种机制来观察用户可访问的文件系统和 Origin Private File System (OPFS) 的变化。这意味着 Web 应用程序无需轮询文件系统即可查找文件或文件夹结构中的更改,从而避免了耗时且浪费资源的操作。

构造函数

FileSystemObserver() 实验性 非标准

创建一个新的 FileSystemObserver 对象实例。

实例方法

disconnect() 实验性 非标准

停止观察文件系统。

observe() 实验性 非标准

开始观察指定文件或目录的变化。

示例

注意: 有关完整的可用示例,请查看 File System Observer Demo源代码)。

初始化 FileSystemObserver

在开始观察文件或目录更改之前,您需要初始化一个 FileSystemObserver 来处理观察。这可以通过 FileSystemObserver() 构造函数完成,该构造函数接受一个回调函数作为参数。

js
const observer = new FileSystemObserver(callback);

可以根据需要定义 回调函数 的主体,以返回和处理文件更改的观察结果。

js
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() 方法来开始观察文件系统条目的更改。

通过将 FileSystemFileHandleFileSystemDirectoryHandle 传递给 observe(),您可以观察用户可访问的文件系统或 Origin Private File System (OPFS) 中的文件或目录。例如,当使用 Window.showSaveFilePicker()Window.showDirectoryPicker() 要求用户选择文件或目录时,可以返回这些对象的实例。

js
// 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 的更改。

js
// 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()

js
observer.disconnect();

规范

目前不是规范的一部分。请参阅 https://github.com/whatwg/fs/pull/165 以获取相关的规范 PR。

浏览器兼容性

另见