Created
April 24, 2020 03:17
-
-
Save aphelionz/8edb09f9708270373a2b239e51261998 to your computer and use it in GitHub Desktop.
For the medium article, link TODO
This file contains hidden or 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
// 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