StorageManager: getDirectory() 方法
注意:此功能在 Web Workers 中可用。
getDirectory() 方法是 StorageManager 接口的一个方法,用于获取一个 FileSystemDirectoryHandle 对象引用,该对象允许访问存储在 源私有文件系统 (OPFS) 中的目录及其内容。
语法
js
getDirectory()
参数
无。
返回值
一个 Promise,它会解析为一个 FileSystemDirectoryHandle 对象。
异常
SecurityErrorDOMException-
如果浏览器无法将请求的目录映射到本地 OPFS,例如由于存储或内存限制,则会抛出此错误。在某些浏览器中,如果
getDirectory()在隐私浏览模式下被调用,也会抛出此错误。 UnknownErrorDOMException-
在某些浏览器中,如果
getDirectory()在隐私浏览模式下被调用,则会抛出此错误。
示例
以下异步事件处理函数包含在 Web Worker 中。在接收到主线程的消息后,它会:
- 使用
getDirectory()获取一个代表 OPFS 根目录的FileSystemDirectoryHandle,并将其存储在root变量中。 - 使用
FileSystemDirectoryHandle.getFileHandle()获取一个文件句柄。 - 使用
FileSystemFileHandle.createSyncAccessHandle()创建一个同步文件访问句柄。 - 获取文件大小并创建一个
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() 被错误地指定为异步方法,并且一些旧版本的浏览器以这种方式实现它们。然而,所有支持这些方法的当前浏览器都将其实现为同步方法。
规范
| 规范 |
|---|
| 文件系统 # dom-storagemanager-getdirectory |
浏览器兼容性
加载中…