Skip to content

Instantly share code, notes, and snippets.

@carsonfarmer
Last active June 21, 2018 20:05
Show Gist options
  • Save carsonfarmer/a0ac7639b99c15599ec7cf868953d2ce to your computer and use it in GitHub Desktop.
Save carsonfarmer/a0ac7639b99c15599ec7cf868953d2ce to your computer and use it in GitHub Desktop.
Update to main.js IPFS Dapp example
const setup = async () => {
// The root IPFS CID for our xkcd archive
const xkcdRoot = '/ipfs/QmS74HhZt3ZekqUDqdttSgMsHwYQ6miDLwGUHy6pp4qLyD'
// Pick and random comic between 1 and 2003 (which is the latest in the archive)
const comicNumber = Math.floor(Math.random() * 2003) + 1
try {
// Create IPFS peer
const ipfs = await getIpfs()
// Connect to public peer pinning xkcd comics (might not be needed)
await ipfs.swarm.connect(
'/dns4/ipfs.carsonfarmer.com/tcp/4002/wss/ipfs/Qmf6Wp6McAKm5oRYUPndLaAs5tnADASyJJZ3HkhzPmJJvY'
)
// Now, fetch files...
const files = await ipfs.files.get(`${xkcdRoot}/${comicNumber}`)
for (let file of files) {
if (file.name.endsWith('.png')) { // We have our image!
// Extract binary file contents
const content = String.fromCharCode.apply(null, file.content)
// Convert to base64 encoded string
const encoded = btoa(content)
// Create new image tag element
const image = document.createElement('img')
image.setAttribute('id', 'image')
// Set image source to data uri from image data
image.setAttribute('src', `data:image/png;base64,${encoded}`)
// Add image to 'main' div
document.getElementById('main').appendChild(image)
break // We have what we want, break outta here
}
}
} catch(err) {
console.log(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment