FileSystemDirectoryHandle: getDirectoryHandle() 方法

Baseline 已广泛支持

此功能已成熟,并可在许多设备和浏览器版本上运行。自 2023 年 3 月以来,它已在各种浏览器中可用。

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

注意:此功能在 Web Workers 中可用。

FileSystemDirectoryHandle 接口的 getDirectoryHandle() 方法会返回一个 FileSystemDirectoryHandle,用于表示在调用该方法的目录句柄中,名为指定名称的子目录。

语法

js
getDirectoryHandle(name)
getDirectoryHandle(name, options)

参数

name

一个字符串,表示您希望检索的子目录的 FileSystemHandle.name

options 可选

一个可选对象,包含检索到的子目录的选项。选项如下:

create 可选

一个布尔值,默认为 false。如果设置为 true,则在找不到目录时,会创建并返回指定名称的目录。

返回值

一个 Promise,它会解析为一个 FileSystemDirectoryHandle

异常

NotAllowedError DOMException

如果在 create 选项设置为 true 时,句柄的 PermissionStatus.state 不是 'granted' 模式(readwrite),或者在 create 选项设置为 false 时,不是 read 模式,则会抛出此错误。

TypeError

如果指定的名称不是有效字符串,或者包含会干扰本地文件系统的字符,则会抛出此错误。

TypeMismatchError DOMException

如果返回的条目是一个文件而不是一个目录,则会抛出此错误。

NotFoundError DOMException

如果当前条目未找到,或者目标目录不存在且 create 选项设置为 false,则会抛出此错误。

示例

下面的示例会返回指定名称的目录句柄,如果目录不存在则会创建它。

js
const dirName = "directoryToGetName";

// assuming we have a directory handle: 'currentDirHandle'
const subDir = await currentDirHandle.getDirectoryHandle(dirName, {
  create: true,
});

规范

规范
文件系统
# api-filesystemdirectoryhandle-getdirectoryhandle

浏览器兼容性

另见