概述摘要索引有助于去重与快速定位。本文提供索引建立与查重方案。建立与查重function openDB(name) { return new Promise((resolve, reject) => { const r = indexedDB.open(name, 1); r.onupgradeneeded = () => { const db = r.result; const s = db.createObjectStore('hash', { keyPath:'hash' }); s.createIndex('byPath','path'); }; r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); }); } async function sha256(bytes) { const buf = await crypto.subtle.digest('SHA-256', bytes); return Array.from(new Uint8Array(buf)).map(x=>x.toString(16).padStart(2,'0')).join(''); } async function indexFile(path) { const root = await navigator.storage.getDirectory(); const seg = path.split('/'); let dir = root; for (let i=0;i<seg.length-1;i++) dir = await dir.getDirectoryHandle(seg[i]); const fh = await dir.getFileHandle(seg[seg.length-1]); const file = await fh.getFile(); const hex = await sha256(new Uint8Array(await file.arrayBuffer())); const db = await openDB('opfs-hash'); const tx = db.transaction('hash','readwrite'); tx.objectStore('hash').put({ hash: hex, path }); await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); }); db.close(); return hex; } async function isDuplicate(hex) { const db = await openDB('opfs-hash'); const tx = db.transaction('hash','readonly'); const req = tx.objectStore('hash').get(hex); const rec = await new Promise((res, rej) => { req.onsuccess = () => res(req.result); req.onerror = () => rej(req.error); }); db.close(); return !!rec; }

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
1.702189s