files/en-us/web/api/filesystemdirectoryhandle/index.md
{{securecontext_header}}{{APIRef("File System API")}}{{AvailableInWorkers}}
The FileSystemDirectoryHandle interface of the {{domxref("File System API", "File System API", "", "nocode")}} provides a handle to a file system directory.
The interface can be accessed via the {{domxref('window.showDirectoryPicker()')}}, {{domxref('StorageManager.getDirectory()')}}, {{domxref('DataTransferItem.getAsFileSystemHandle()')}}, and {{domxref('FileSystemDirectoryHandle.getDirectoryHandle()')}} methods.
{{InheritanceDiagram}}
Inherits properties from its parent, {{DOMxRef("FileSystemHandle")}}.
Inherits methods from its parent, {{DOMxRef("FileSystemHandle")}}.
Regular methods:
FileSystemDirectoryHandle for a subdirectory with the specified name within the directory handle on which the method is called.Asynchronous iterator methods:
[key, value] pairs.FileSystemDirectoryHandle.FileSystemDirectoryHandle object.FileSystemDirectoryHandle[Symbol.asyncIterator]()
[key, value] pairs.The following example returns a directory handle with the specified name; if the directory does not already exist it is created.
const dirName = "directoryToGetName";
// assuming we have a directory handle: 'currentDirHandle'
const subDir = await currentDirHandle.getDirectoryHandle(dirName, {
create: true,
});
The following asynchronous function uses resolve() to find the path to a chosen file, relative to a specified directory handle.
async function returnPathDirectories(directoryHandle) {
// Get a file handle by showing a file picker:
const handle = await self.showOpenFilePicker();
if (!handle) {
// User cancelled, or otherwise failed to open a file.
return;
}
// Check if handle exists inside our directory handle
const relativePaths = await directoryHandle.resolve(handle);
if (relativePath === null) {
// Not inside directory handle
} else {
// relativePath is an array of names, giving the relative path
for (const name of relativePaths) {
// log each entry
console.log(name);
}
}
}
The following example scans recursively through a directory to return {{domxref('FileSystemFileHandle')}} objects for each file in that directory:
async function* getFilesRecursively(entry) {
if (entry.kind === "file") {
const file = await entry.getFile();
if (file !== null) {
file.relativePath = getRelativePath(entry);
yield file;
}
} else if (entry.kind === "directory") {
for await (const handle of entry.values()) {
yield* getFilesRecursively(handle);
}
}
}
for await (const fileHandle of getFilesRecursively(directoryHandle)) {
console.log(fileHandle);
}
{{Specifications}}
{{Compat}}