概述OPFS 的同步访问句柄提升 Worker 场景下的读写性能。本文给出能力检测与读写示例,并在不支持时退化到异步接口。Worker 内能力检测与读写async function writeWithSyncHandle(path, bytes) {

const root = await navigator.storage.getDirectory();

const segments = path.split('/').filter(Boolean);

let dir = root;

for (let i = 0; i < segments.length - 1; i++) {

dir = await dir.getDirectoryHandle(segments[i], { create: true });

}

const name = segments[segments.length - 1];

const fh = await dir.getFileHandle(name, { create: true });

if (typeof fh.createSyncAccessHandle !== 'function') {

const w = await fh.createWritable();

await w.write(bytes);

await w.close();

return;

}

const h = await fh.createSyncAccessHandle();

h.write(bytes, { at: 0 });

h.flush();

h.close();

}

async function readWithSyncHandle(path) {

const root = await navigator.storage.getDirectory();

const segments = path.split('/').filter(Boolean);

let dir = root;

for (let i = 0; i < segments.length - 1; i++) {

dir = await dir.getDirectoryHandle(segments[i]);

}

const name = segments[segments.length - 1];

const fh = await dir.getFileHandle(name);

if (typeof fh.createSyncAccessHandle !== 'function') {

const file = await fh.getFile();

const buf = await file.arrayBuffer();

return new Uint8Array(buf);

}

const h = await fh.createSyncAccessHandle();

const size = h.getSize();

const buf = new Uint8Array(size);

h.read(buf, { at: 0 });

h.close();

return buf;

}

主线程与 Worker 集成function startOPFSWorker() {

const worker = new Worker('opfs-worker.js');

const data = new Uint8Array([1,2,3,4]);

worker.postMessage({ type: 'write', path: 'data/a.bin', payload: data }, [data.buffer]);

}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部