概述为 OPFS 建立元数据索引可提升检索效率。本文提供遍历与索引写入、查询示例。建立索引function openDB(name) { return new Promise((resolve, reject) => { const r = indexedDB.open(name, 1); r.onupgradeneeded = () => { const db = r.result; const s = db.createObjectStore('files', { keyPath:'path' }); s.createIndex('bySize','size'); s.createIndex('byTs','ts'); }; r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); }); } async function indexOPFS() { const root = await navigator.storage.getDirectory(); const db = await openDB('opfs-index'); const tx = db.transaction('files','readwrite'); await (async function walk(dir, base='') { for await (const [name, h] of dir.entries()) { const p = base ? base + '/' + name : name; if (h.kind === 'file') { const f = await h.getFile(); tx.objectStore('files').put({ path: p, size: f.size, ts: f.lastModified }); } else await walk(await dir.getDirectoryHandle(name), p); } })(root); await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); }); db.close(); } 查询示例async function searchByName(keyword) { const db = await openDB('opfs-index'); const tx = db.transaction('files','readonly'); const s = tx.objectStore('files'); const req = s.openCursor(); const out = []; await new Promise((res, rej) => { req.onsuccess = e => { const c = e.target.result; if (c) { if (c.key.includes(keyword)) out.push(c.value); c.continue(); } else res(); }; req.onerror = () => rej(req.error); }); db.close(); return out; }

发表评论 取消回复