-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path2-replicate-hypercores.js
More file actions
70 lines (55 loc) · 1.9 KB
/
2-replicate-hypercores.js
File metadata and controls
70 lines (55 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const chalk = require('chalk')
const { Client: HyperspaceClient } = require('hyperspace')
start()
async function start () {
// Create a client that's connected to the "local" peer.
const localClient = new HyperspaceClient({
host: 'hyperspace-demo-1'
})
// Create a client that's connected to the "remote" peer.
const remoteClient = new HyperspaceClient({
host: 'hyperspace-demo-2'
})
// Now let's replicate a Hypercore between both servers.
// First, create the Hypercore on the local instance.
var sharedKey = null
{
// Create a new RemoteCorestore.
const store = localClient.corestore()
// Create a fresh Remotehypercore.
const core = store.get({
valueEncoding: 'utf-8'
})
// Append two blocks to the RemoteHypercore.
await core.append(['hello', 'world'])
// Log when the core has any new peers.
core.on('peer-add', () => {
console.log(chalk.blue('(local) Replicating with a new peer.'))
})
// Start seeding the Hypercore on the Hyperswarm network.
localClient.replicate(core)
sharedKey = core.key
}
// Now, create a clone on the remote instance, and read the first two blocks.
{
// Create a new RemoteCorestore.
const store = remoteClient.corestore()
// Create a fresh Remotehypercore.
// Here we'll get a core using the shared key from above.
const core = store.get({
key: sharedKey,
valueEncoding: 'utf-8'
})
// Log when the core has any new peers.
core.on('peer-add', () => {
console.log(chalk.blue('(remote) Replicating with a new peer.'))
})
// Start seeding the Hypercore (this will connect to the first Hyperspace instance)
remoteClient.replicate(core)
// The core should now have one connected peer, so we can read the first two blocks.
console.log(chalk.green('First two blocks:', [
await core.get(0),
await core.get(1)
]))
}
}