FileSystemDirectoryHandle
注意:此功能在 Web Workers 中可用。
FileSystemDirectoryHandle 介面是 檔案系統 API 的一部分,它提供了對檔案系統目錄的控制代碼。
該介面可以透過 window.showDirectoryPicker()、StorageManager.getDirectory()、DataTransferItem.getAsFileSystemHandle() 和 FileSystemDirectoryHandle.getDirectoryHandle() 方法訪問。
例項屬性
繼承其父級 FileSystemHandle 的屬性。
例項方法
繼承其父級 FileSystemHandle 的方法。
常規方法
FileSystemDirectoryHandle.getDirectoryHandle()-
返回一個
Promise,該Promise會被一個FileSystemDirectoryHandle兌現,該FileSystemDirectoryHandle代表在呼叫該方法的目錄控制代碼內具有指定名稱的子目錄。 FileSystemDirectoryHandle.getFileHandle()-
返回一個
Promise,該Promise會被一個FileSystemFileHandle兌現,該FileSystemFileHandle代表在呼叫該方法的目錄內具有指定名稱的檔案。 FileSystemDirectoryHandle.removeEntry()-
如果目錄控制代碼包含名為指定名稱的檔案或目錄,則嘗試非同步刪除該條目。
FileSystemDirectoryHandle.resolve()-
返回一個
Promise,該Promise會被一個Array兌現,該陣列包含從父控制代碼到指定子條目的目錄名稱,其中子條目的名稱是最後一個數組項。
非同步迭代器方法
FileSystemDirectoryHandle.entries()-
返回給定物件自身可列舉屬性的 `[key, value]` 對的新的非同步迭代器。
FileSystemDirectoryHandle.keys()-
返回一個包含
FileSystemDirectoryHandle中每個條目鍵的新非同步迭代器。 FileSystemDirectoryHandle.values()-
返回一個包含
FileSystemDirectoryHandle物件中每個索引值的新的非同步迭代器。 FileSystemDirectoryHandle[Symbol.asyncIterator]()-
返回給定物件自身可列舉屬性的 `[key, value]` 對的新的非同步迭代器。
示例
返回目錄控制代碼
以下示例返回一個具有指定名稱的目錄控制代碼;如果目錄不存在,則會建立它。
const dirName = "directoryToGetName";
// assuming we have a directory handle: 'currentDirHandle'
const subDir = await currentDirHandle.getDirectoryHandle(dirName, {
create: true,
});
返回檔案路徑
以下非同步函式使用 resolve() 方法查詢相對於指定目錄控制代碼的選定檔案的路徑。
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);
}
}
}
返回目錄中所有檔案的控制代碼
以下示例遞迴地掃描目錄,返回該目錄中每個檔案的 FileSystemFileHandle 物件。
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);
}
規範
| 規範 |
|---|
| 檔案系統 # api-filesystemdirectoryhandle |
瀏覽器相容性
載入中…