Last active
February 16, 2023 19:44
-
-
Save Anyass3/055cdedaa0c091bc9e11aac2a8c9ad6b to your computer and use it in GitHub Desktop.
hyperdrive: Display entries and prefixes with same path in directory listing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { join } from 'path'; | |
import Corestore from 'corestore'; | |
import RAM from 'random-access-memory'; | |
import Hyperdrive from 'hyperdrive'; | |
async function iteratorPeek(files, folder, prev) { | |
let node = null, nextNode = null; | |
/** Two nodes in case a file and a folder have the same name*/ | |
const ite = files.createRangeIterator({ | |
gt: folder + prev, | |
lt: folder + '0', limit: 2 | |
}); | |
try { | |
await ite.open(); | |
node = await ite.next(); | |
const next = await ite.next(); | |
if (next?.key.startsWith(node.key)) { | |
nextNode = { key: node.key + '/' }; | |
} | |
} | |
finally { | |
await ite.close(); | |
} | |
return { node, nextNode }; | |
} | |
function getNodeName(node, folder) { | |
const suffix = node.key.slice(folder.length + 1); | |
const i = suffix.indexOf('/'); | |
const name = i === -1 ? suffix : suffix.slice(0, i); | |
const isFile = node.key.endsWith(name); | |
return { name, dir: !isFile ? name + '/' : null, pathname: join(folder, name, !isFile ? '/' : '') }; | |
} | |
async function* shallowReadGenerator(files, folder, keys) { | |
let prev = '/'; | |
while (true) { | |
const { node, nextNode } = await iteratorPeek(files, folder, prev); | |
if (!node) { | |
break; | |
} | |
const { name, dir, pathname } = getNodeName(node, folder); | |
prev = '/' + name + '0'; | |
if (nextNode) { | |
yield keys ? node : name; | |
yield keys ? { key: join(pathname, '/') } : name + '/'; | |
} | |
else yield keys ? { key: pathname } : dir || name; | |
} | |
} | |
const corestore = new Corestore((() => { | |
return new RAM(); | |
})) | |
const drive = new Hyperdrive(corestore); | |
await drive.put('/a/e', Buffer.from('')) | |
await drive.put('/a/e/oom', Buffer.from('')) | |
await drive.put('/a/b/hmm', Buffer.from('hmmm')) | |
await drive.put('/a/b', Buffer.from('hmmm')) | |
await drive.put('/a/hi', Buffer.from('hi')) | |
for await (const name of shallowReadGenerator(drive.files, '/a')) { | |
console.log(name) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
logs
b
b/
e
e/
hi