Skip to content

Instantly share code, notes, and snippets.

@cblgh
Last active July 10, 2017 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cblgh/abe726c09a4fcebbb9e6188a1304a05e to your computer and use it in GitHub Desktop.
Save cblgh/abe726c09a4fcebbb9e6188a1304a05e to your computer and use it in GitHub Desktop.
connect & read between two hyperdb instances across a network
// COMPUTER 1
var ram = require("random-access-memory") // store remote db in ram. it's nice for testing bc doesnt create a bunch of files
var hyperdiscovery = require("hyperdiscovery")
var hyperdb = require("hyperdb")
var hypercore = require("hypercore")
// local.key is d5d0b189af6b981ab7942c3d71103e9a1cbfa32e203220e830b7a16deac6cc43
var local = hypercore("./local-db", {valueEncoding: "json", sparse: true})
// pass in feeds in same sequence on both machines
var db = hyperdb([
// feed 1 = computer 1
local,
// feed 2 = computer 2 (id is computer 2's public key, see "local key" logging below
hypercore(ram, "5c73d8199d83875b62b19b28893b374189e439e760dc070497cfbd643bfb8fbe", {valueEncoding: "json", sparse: true})
])
var key = process.argv[2] || "test-key"
db.ready(function () {
var id = local.key.toString("hex")
console.log("local key", id)
var sw = hyperdiscovery(db, {live: true})
sw.on("connection", function(peer, type) {
console.log("we got a connection")
})
// get a value
db.get(key, function(err, nodes) {
if (err) {console.log(err); return;}
if (nodes && nodes[0]) {
console.log(nodes[0])
}
})
// add a value
db.put(key, "a cool value", function(err, nodes) {
if (err) {console.log(err); return;}
})
})
.....
// COMPUTER 2
var ram = require("random-access-memory")
var hyperdiscovery = require("hyperdiscovery")
var hyperdb = require("hyperdb")
var hypercore = require("hypercore")
// local.key is 5c73d8199d83875b62b19b28893b374189e439e760dc070497cfbd643bfb8fbe
var local = hypercore("./local-db", {valueEncoding: "json", sparse: true})
// pass in feeds in same sequence on both machines
var db = hyperdb([
// feed 1 = computer 1
hypercore(ram, "d5d0b189af6b981ab7942c3d71103e9a1cbfa32e203220e830b7a16deac6cc43", {valueEncoding: "json", sparse: true}),
// feed 2 = computer 2
local
])
var key = process.argv[2] || "test-key"
db.ready(function () {
var id = local.key.toString("hex")
console.log("local key", id)
var sw = hyperdiscovery(db, {live: true})
sw.on("connection", function(peer, type) {
console.log("we got a connection")
})
// get a value
db.get(key, function(err, nodes) {
if (err) {console.log(err); return;}
if (nodes && nodes[0]) {
console.log(nodes[0])
}
})
// add a value
db.put(key, "a cool value", function(err, nodes) {
if (err) {console.log(err); return;}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment