文件系统标准引入了源私有文件系统 (OPFS) 作为页面源私有的存储端点,用户不可见,它提供对一种特殊类型文件的可选访问,这种文件针对性能进行了高度优化。
浏览器支持
源私有文件系统受现代浏览器支持,并由 Web 超文本应用技术工作组 (WHATWG) 在 文件系统实时标准 中进行了标准化。
动机
当您想到计算机上的文件时,您可能会想到文件层次结构:文件组织在文件夹中,您可以使用操作系统的文件资源管理器来浏览这些文件夹。例如,在 Windows 上,对于名为 Tom 的用户,他们的待办事项列表可能位于 C:\Users\Tom\Documents\ToDo.txt
中。在此示例中,ToDo.txt
是文件名,而 Users
、Tom
和 Documents
是文件夹名称。Windows 上的 `C:` 代表驱动器的根目录。
在 Web 上使用文件的传统方式
要在 Web 应用程序中编辑待办事项列表,通常的流程如下
- 用户将文件上传到服务器,或者使用
<input type="file">
在客户端打开它。 - 用户进行更改,然后使用注入的
<a download="ToDo.txt>
下载结果文件,您可以通过 JavaScript 以编程方式click()
。 - 要打开文件夹,您可以使用
<input type="file" webkitdirectory>
中的特殊属性,尽管它具有专有名称,但实际上具有通用的浏览器支持。
在 Web 上使用文件的现代方式
此流程不能代表用户如何考虑编辑文件,并且意味着用户最终得到其输入文件的下载副本。因此,文件系统访问 API 引入了三个选择器方法 - showOpenFilePicker()
、showSaveFilePicker()
和 showDirectoryPicker()
- 它们完全按照其名称所暗示的那样执行。它们启用了如下流程
- 使用
showOpenFilePicker()
打开ToDo.txt
,并获取FileSystemFileHandle
对象。 - 从
FileSystemFileHandle
对象中,通过调用文件句柄的getFile()
方法获取File
。 - 修改文件,然后在句柄上调用
requestPermission({mode: 'readwrite'})
。 - 如果用户接受权限请求,则将更改保存回原始文件。
- 或者,调用
showSaveFilePicker()
并让用户选择一个新文件。(如果用户选择以前打开的文件,其内容将被覆盖。)对于重复保存,您可以保留文件句柄,这样您就不必再次显示文件保存对话框。
在 Web 上使用文件的限制
可通过这些方法访问的文件和文件夹位于可以称为用户可见文件系统的位置。从 Web 保存的文件,特别是可执行文件,标有 Web 标记,因此操作系统可以在执行潜在危险文件之前显示额外的警告。作为额外的安全功能,从 Web 获取的文件也受到 安全浏览 的保护,为了简单起见,并在本文的上下文中,您可以将其视为基于云的病毒扫描。当您使用文件系统访问 API 将数据写入文件时,写入不是就地进行的,而是使用临时文件。除非文件通过所有这些安全检查,否则不会修改文件本身。正如您可以想象的那样,尽管在可能的情况下应用了改进,例如 在 macOS 上,但这项工作使文件操作相对较慢。尽管如此,每次 write()
调用都是独立的,因此在底层,它会打开文件,查找给定的偏移量,最后写入数据。
文件作为处理的基础
同时,文件是记录数据的绝佳方式。例如,SQLite 将整个数据库存储在单个文件中。另一个示例是图像处理中使用的 mipmap。Mipmap 是预先计算的、优化的图像序列,每个图像都是前一个图像的逐步降低分辨率的表示,这使得许多操作(如缩放)更快。那么,Web 应用程序如何才能获得文件的好处,但又避免基于 Web 的文件处理的性能成本呢?答案是源私有文件系统。
用户可见文件系统与源私有文件系统
与使用操作系统文件资源管理器浏览的用户可见文件系统不同,您可以使用文件和文件夹进行读取、写入、移动和重命名,而源私有文件系统不打算供用户查看。顾名思义,源私有文件系统中的文件和文件夹是私有的,更具体地说,对于站点的 源 来说是私有的。通过在 DevTools 控制台中键入 location.origin
来发现页面的源。例如,页面 https://developer.chrome.com/articles/
的源是 https://developer.chrome.com
(也就是说,/articles
部分不是源的一部分)。您可以在 理解“同站点”和“同源” 中阅读有关源理论的更多信息。共享同一源的所有页面都可以看到相同的源私有文件系统数据,因此 https://developer.chrome.com/docs/extensions/mv3/getstarted/extensions-101/
可以看到与上一个示例相同的详细信息。每个源都有其自己独立的源私有文件系统,这意味着 https://developer.chrome.com
的源私有文件系统与例如 https://webdev.ac.cn
的源私有文件系统完全不同。在 Windows 上,用户可见文件系统的根目录是 C:\\
。源私有文件系统的等效项是每个源的初始空根目录,通过调用异步方法 navigator.storage.getDirectory()
访问。有关用户可见文件系统和源私有文件系统的比较,请参见下图。该图显示,除了根目录之外,其他所有内容在概念上都是相同的,具有文件和文件夹的层次结构,可以根据您的数据和存储需求进行组织和排列。
源私有文件系统的具体细节
与浏览器中的其他存储机制(例如,localStorage 或 IndexedDB)一样,源私有文件系统也受到浏览器配额限制的约束。当用户 清除所有浏览数据 或 所有站点数据 时,源私有文件系统也将被删除。调用 navigator.storage.estimate()
,并在结果响应对象中查看 usage
条目,以查看您的应用已消耗多少存储空间,这在 usageDetails
对象中按存储机制细分,您需要在其中专门查看 fileSystem
条目。由于源私有文件系统对用户不可见,因此没有权限提示,也没有安全浏览检查。
获取对根目录的访问权限
要获取对根目录的访问权限,请运行以下命令。您最终会得到一个空目录句柄,更具体地说,是 FileSystemDirectoryHandle
。
const opfsRoot = await navigator.storage.getDirectory();
// A FileSystemDirectoryHandle whose type is "directory"
// and whose name is "".
console.log(opfsRoot);
主线程或 Web Worker
使用源私有文件系统有两种方式:在主线程上或在Web Worker中。Web Worker 无法阻止主线程,这意味着在这种情况下,API 可以是同步的,这通常在主线程上是不允许的模式。同步 API 可以更快,因为它们避免了处理 Promise,并且文件操作通常在可以编译为 WebAssembly 的 C 等语言中是同步的。
// This is synchronous C code.
FILE *f;
f = fopen("example.txt", "w+");
fputs("Some text\n", f);
fclose(f);
如果您需要最快的文件操作,或者您处理 WebAssembly,请跳至在 Web Worker 中使用源私有文件系统。否则,您可以继续阅读。
在主线程上使用源私有文件系统
创建新文件和文件夹
获得根文件夹后,分别使用 getFileHandle()
和 getDirectoryHandle()
方法创建文件和文件夹。通过传递 {create: true}
,如果文件或文件夹不存在,则会创建它。通过使用新创建的目录作为起点调用这些函数,构建文件层次结构。
const fileHandle = await opfsRoot
.getFileHandle('my first file', {create: true});
const directoryHandle = await opfsRoot
.getDirectoryHandle('my first folder', {create: true});
const nestedFileHandle = await directoryHandle
.getFileHandle('my first nested file', {create: true});
const nestedDirectoryHandle = await directoryHandle
.getDirectoryHandle('my first nested folder', {create: true});
访问现有文件和文件夹
如果您知道现有文件和文件夹的名称,可以通过调用 getFileHandle()
或 getDirectoryHandle()
方法并传入文件或文件夹的名称来访问它们。
const existingFileHandle = await opfsRoot.getFileHandle('my first file');
const existingDirectoryHandle = await opfsRoot
.getDirectoryHandle('my first folder');
获取与文件句柄关联的文件以进行读取
FileSystemFileHandle
表示文件系统上的文件。要获取关联的 File
,请使用 getFile()
方法。File
对象是 Blob
的一种特定类型,可以在 Blob
可以使用的任何上下文中使用。特别是,FileReader
、URL.createObjectURL()
、createImageBitmap()
和 XMLHttpRequest.send()
都接受 Blobs
和 Files
。如果您愿意,从 FileSystemFileHandle
获取 File
会“释放”数据,因此您可以访问它并使其可用于用户可见的文件系统。
const file = await fileHandle.getFile();
console.log(await file.text());
通过流式传输写入文件
通过调用 createWritable()
将数据流式传输到文件中,这将创建一个 FileSystemWritableFileStream
,然后您可以将内容 write()
到该流中。最后,您需要 close()
流。
const contents = 'Some text';
// Get a writable stream.
const writable = await fileHandle.createWritable();
// Write the contents of the file to the stream.
await writable.write(contents);
// Close the stream, which persists the contents.
await writable.close();
删除文件和文件夹
通过调用其文件或目录句柄的特定 remove()
方法删除文件和文件夹。要删除包含所有子文件夹的文件夹,请传递 {recursive: true}
选项。
await fileHandle.remove();
await directoryHandle.remove({recursive: true});
作为替代方案,如果您知道要删除的文件或文件夹在目录中的名称,请使用 removeEntry()
方法。
directoryHandle.removeEntry('my first nested file');
移动和重命名文件和文件夹
使用 move()
方法重命名和移动文件和文件夹。移动和重命名可以同时发生,也可以单独发生。
// Rename a file.
await fileHandle.move('my first renamed file');
// Move a file to another directory.
await fileHandle.move(nestedDirectoryHandle);
// Move a file to another directory and rename it.
await fileHandle
.move(nestedDirectoryHandle, 'my first renamed and now nested file');
解析文件或文件夹的路径
要了解给定文件或文件夹相对于引用目录的位置,请使用 resolve()
方法,并将 FileSystemHandle
作为参数传递给它。要获取源私有文件系统中文件或文件夹的完整路径,请使用通过 navigator.storage.getDirectory()
获取的根目录作为引用目录。
const relativePath = await opfsRoot.resolve(nestedDirectoryHandle);
// `relativePath` is `['my first folder', 'my first nested folder']`.
检查两个文件或文件夹句柄是否指向同一个文件或文件夹
有时您有两个句柄,但不知道它们是否指向同一个文件或文件夹。要检查是否是这种情况,请使用 isSameEntry()
方法。
fileHandle.isSameEntry(nestedFileHandle);
// Returns `false`.
列出文件夹的内容
FileSystemDirectoryHandle
是一个异步迭代器,您可以使用 for await…of
循环对其进行迭代。作为异步迭代器,它还支持 entries()
、values()
和 keys()
方法,您可以根据需要的信息从中进行选择
for await (let [name, handle] of directoryHandle) {}
for await (let [name, handle] of directoryHandle.entries()) {}
for await (let handle of directoryHandle.values()) {}
for await (let name of directoryHandle.keys()) {}
递归列出文件夹及其所有子文件夹的内容
处理异步循环和与递归配对的函数很容易出错。以下函数可以作为起点,用于列出文件夹及其所有子文件夹的内容,包括所有文件及其大小。如果不需要文件大小,您可以简化该函数,在它说 directoryEntryPromises.push
的地方,不推送 handle.getFile()
Promise,而是直接推送 handle
。
const getDirectoryEntriesRecursive = async (
directoryHandle,
relativePath = '.',
) => {
const fileHandles = [];
const directoryHandles = [];
const entries = {};
// Get an iterator of the files and folders in the directory.
const directoryIterator = directoryHandle.values();
const directoryEntryPromises = [];
for await (const handle of directoryIterator) {
const nestedPath = `${relativePath}/${handle.name}`;
if (handle.kind === 'file') {
fileHandles.push({ handle, nestedPath });
directoryEntryPromises.push(
handle.getFile().then((file) => {
return {
name: handle.name,
kind: handle.kind,
size: file.size,
type: file.type,
lastModified: file.lastModified,
relativePath: nestedPath,
handle
};
}),
);
} else if (handle.kind === 'directory') {
directoryHandles.push({ handle, nestedPath });
directoryEntryPromises.push(
(async () => {
return {
name: handle.name,
kind: handle.kind,
relativePath: nestedPath,
entries:
await getDirectoryEntriesRecursive(handle, nestedPath),
handle,
};
})(),
);
}
}
const directoryEntries = await Promise.all(directoryEntryPromises);
directoryEntries.forEach((directoryEntry) => {
entries[directoryEntry.name] = directoryEntry;
});
return entries;
};
在 Web Worker 中使用源私有文件系统
如前所述,Web Worker 无法阻止主线程,这就是为什么在这种情况下允许使用同步方法。
获取同步访问句柄
最快的文件操作的入口点是 FileSystemSyncAccessHandle
,它通过调用 createSyncAccessHandle()
从常规 FileSystemFileHandle
获取。
const fileHandle = await opfsRoot
.getFileHandle('my highspeed file.txt', {create: true});
const syncAccessHandle = await fileHandle.createSyncAccessHandle();
同步就地文件方法
获得同步访问句柄后,您就可以访问快速的就地文件方法,这些方法都是同步的。
getSize()
:返回文件的大小(以字节为单位)。write()
:将缓冲区的内容写入文件,可以选择在给定的偏移量处写入,并返回写入的字节数。检查返回的写入字节数允许调用者检测和处理错误和部分写入。read()
:将文件的内容读取到缓冲区中,可以选择在给定的偏移量处读取。truncate()
:将文件大小调整为给定大小。flush()
:确保文件的内容包含通过write()
完成的所有修改。close()
:关闭访问句柄。
这是一个使用上述所有方法的示例。
const opfsRoot = await navigator.storage.getDirectory();
const fileHandle = await opfsRoot.getFileHandle('fast', {create: true});
const accessHandle = await fileHandle.createSyncAccessHandle();
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
// Initialize this variable for the size of the file.
let size;
// The current size of the file, initially `0`.
size = accessHandle.getSize();
// Encode content to write to the file.
const content = textEncoder.encode('Some text');
// Write the content at the beginning of the file.
accessHandle.write(content, {at: size});
// Flush the changes.
accessHandle.flush();
// The current size of the file, now `9` (the length of "Some text").
size = accessHandle.getSize();
// Encode more content to write to the file.
const moreContent = textEncoder.encode('More content');
// Write the content at the end of the file.
accessHandle.write(moreContent, {at: size});
// Flush the changes.
accessHandle.flush();
// The current size of the file, now `21` (the length of
// "Some textMore content").
size = accessHandle.getSize();
// Prepare a data view of the length of the file.
const dataView = new DataView(new ArrayBuffer(size));
// Read the entire file into the data view.
accessHandle.read(dataView);
// Logs `"Some textMore content"`.
console.log(textDecoder.decode(dataView));
// Read starting at offset 9 into the data view.
accessHandle.read(dataView, {at: 9});
// Logs `"More content"`.
console.log(textDecoder.decode(dataView));
// Truncate the file after 4 bytes.
accessHandle.truncate(4);
将文件从源私有文件系统复制到用户可见的文件系统
如上所述,无法将文件从源私有文件系统移动到用户可见的文件系统,但您可以复制文件。由于 showSaveFilePicker()
仅在主线程上公开,而不在 Worker 线程中公开,因此请确保在那里运行代码。
// On the main thread, not in the Worker. This assumes
// `fileHandle` is the `FileSystemFileHandle` you obtained
// the `FileSystemSyncAccessHandle` from in the Worker
// thread. Be sure to close the file in the Worker thread first.
const fileHandle = await opfsRoot.getFileHandle('fast');
try {
// Obtain a file handle to a new file in the user-visible file system
// with the same name as the file in the origin private file system.
const saveHandle = await showSaveFilePicker({
suggestedName: fileHandle.name || ''
});
const writable = await saveHandle.createWritable();
await writable.write(await fileHandle.getFile());
await writable.close();
} catch (err) {
console.error(err.name, err.message);
}
调试源私有文件系统
在添加内置 DevTools 支持之前(请参阅 crbug/1284595),请使用 OPFS Explorer Chrome 扩展程序来调试源私有文件系统。顺便说一句,上面来自创建新文件和文件夹部分的屏幕截图直接取自该扩展程序。
安装扩展程序后,打开 Chrome DevTools,选择 OPFS Explorer 选项卡,然后您就可以检查文件层次结构了。通过单击文件名将文件从源私有文件系统保存到用户可见的文件系统,并通过单击垃圾桶图标删除文件和文件夹。
演示
在 演示 中查看源私有文件系统的实际效果(如果您安装了 OPFS Explorer 扩展程序),该演示将其用作编译为 WebAssembly 的 SQLite 数据库的后端。请务必查看 Glitch 上的源代码。请注意,下面的嵌入版本不使用源私有文件系统后端(因为 iframe 是跨域的),但是当您在单独的选项卡中打开演示时,它会使用。
结论
正如 WHATWG 所指定的那样,源私有文件系统已经改变了我们在 Web 上使用文件和与之交互的方式。它启用了使用用户可见文件系统无法实现的新用例。所有主要的浏览器供应商 - Apple、Mozilla 和 Google - 都在船上并分享共同的愿景。源私有文件系统的开发在很大程度上是一项协作努力,来自开发者和用户的反馈对于其进展至关重要。当我们继续改进和完善标准时,欢迎以 Issues 或 Pull Requests 的形式在 whatwg/fs 存储库 上提供反馈。
相关链接
致谢
本文由 Austin Sully、Etienne Noël 和 Rachel Andrew 审阅。英雄图片由 Christina Rumpf 在 Unsplash 上提供。