Skip to content

Instantly share code, notes, and snippets.

@martinheidegger
Last active May 10, 2021 04:08
Show Gist options
  • Save martinheidegger/4e4a08e101aa603fc1bc9d7527fa392d to your computer and use it in GitHub Desktop.
Save martinheidegger/4e4a08e101aa603fc1bc9d7527fa392d to your computer and use it in GitHub Desktop.
const Corestore = require('corestore')
const Networker = require('@corestore/networker')
const { mkdir } = require('fs/promises')
let index = 0
async function create () {
index += 1
const dir = `.tmp/${index}`
await mkdir(dir, { recursive: true })
const store = new Corestore(dir)
await store.ready()
const networker = new Networker(store)
return { store, networker }
}
async function run () {
console.log('> Creating stores')
const { networker: networker1, store: store1 } = await create()
const { networker: networker2, store: store2 } = await create()
const core1a = store1.get()
console.log('> Appending to first core')
await append(core1a, 'a')
const core2a = store2.get({ key: core1a.key })
networker1.on('peer-add', (peer) => console.log('nw1-add', peer.remoteAddress))
networker2.on('peer-add', (peer) => console.log('nw2-add', peer.remoteAddress))
networker1.on('stream-closed', () => console.log('nw1-stream-closed'))
networker2.on('stream-closed', () => console.log('nw2-stream-closed'))
console.log('> Configuring first networker')
await networker1.configure(core1a.discoveryKey)
console.log('> Configuring second networker')
await networker2.configure(core2a.discoveryKey)
console.log('> Just for test: see if waiting a bit is relevant before closing')
await new Promise(resolve => setTimeout(resolve, 100))
console.log('> Closing networker 1')
await networker1.close()
console.log('> Closing networker 2')
await networker2.close()
console.log('> Closing store 1')
await store1.close()
console.log('> Closing store 2')
await store2.close()
console.log('> Done.')
}
const append = (core, data) => new Promise((resolve, reject) => {
core.append(data, (err) => err ? reject(err) : resolve())
})
run().catch(error => {
console.error(error.stack)
process.exit(1)
})
{
"main": "index.js",
"dependencies": {
"@corestore/networker": "1.1.0",
"corestore": "5.8.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment