Skip to content

Instantly share code, notes, and snippets.

@andrewosh

andrewosh/README.md

Created May 11, 2020
Embed
What would you like to do?
A smal,l end-to-end example of using Hyperdrive/Hyperswarm to replicate a drive

Note: To keep this even smaller, we're using a small helper module called the hyperswarm replicator, which wraps a few Hyperswarm setup details.

const hyperdrive = require('hyperdrive')
const replicate = require('@hyperswarm/replicator')
const driveToShare = hyperdrive('./writer-storage')
driveToShare.writeFile('hello.txt', 'world', err => {
if (err) return console.error(err)
const swarm = replicate(driveToShare)
process.on('SIGINT', () => swarm.destroy())
// Let's say the drive's key is 1df13252...
const keyString = driveToShare.key.toString('hex')
console.log('Seeding drive:', keyString)
})
const hyperdrive = require('hyperdrive')
const replicate = require('@hyperswarm/replicator')
// Assuming this is the key generated above.
const key = Buffer.from('1df13252...', 'hex')
const driveToRead = hyperdrive('./reader-storage', key)
const swarm = replicate(driveToRead)
process.on('SIGINT', () => swarm.destroy())
driveToRead.on('peer-add', onPeerAdded)
function onPeerAdded () {
const readOpts = { encoding: 'utf-8' }
driveToRead.readFile('hello.txt', readOpts, (err, contents) => {
if (err) return console.error(err)
console.log('Got contents:', contents)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.