Skip to content

Instantly share code, notes, and snippets.

@aphelionz
Created April 24, 2020 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aphelionz/8edb09f9708270373a2b239e51261998 to your computer and use it in GitHub Desktop.
Save aphelionz/8edb09f9708270373a2b239e51261998 to your computer and use it in GitHub Desktop.
For the medium article, link TODO
// author https://github.com/achingbrain
const createFile = async (ipfs, data, chunkSize = 262144) => {
const chunks = []
for (let i = 0; i < data.length; i += chunkSize) {
const unixfs = new UnixFS({
type: 'file',
data: data.slice(i, i + chunkSize)
})
const dagNode = new DAGNode(unixfs.marshal())
const block = await ipfs.block.put(dagNode.serialize())
chunks.push({
unixfs,
size: block.data.length,
cid: block.cid
})
}
if (chunks.length === 1) {
return {
cid: chunks[0].cid,
cumulativeSize: chunks[0].size
}
}
const unixfs = new UnixFS({
type: 'file',
blockSizes: chunks.map(chunk => chunk.unixfs.fileSize())
})
const dagNode = new DAGNode(unixfs.marshal(), chunks.map(chunk => new DAGLink('', chunk.size, chunk.cid)))
const block = await ipfs.block.put(dagNode.serialize())
return {
cid: block.cid,
cumulativeSize: chunks.reduce((acc, curr) => acc + curr.size, 0) + block.data.length
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment