Browse Source

add example from readme

v4
Mathias Buus 5 years ago
parent
commit
b059dd7a76
  1. 6
      example/bootstrap.js
  2. 21
      example/find.js
  3. 15
      example/insert.js
  4. 37
      example/network.js

6
example/bootstrap.js

@ -0,0 +1,6 @@
const dht = require('../')
// Set ephemeral: true so other peers do not add us to the peer list, simply bootstrap
const bootstrap = dht({ ephemeral: true })
bootstrap.listen(10001)

21
example/find.js

@ -0,0 +1,21 @@
const dht = require('../')
const crypto = require('crypto')
const hex = process.argv[2]
const node = dht({ ephemeral: true, bootstrap: ['localhost:10001'] })
node.query('values', Buffer.from(hex, 'hex'))
.on('data', function (data) {
if (data.value && sha256(data.value).toString('hex') === hex) {
// We found the value! Destroy the query stream as there is no need to continue.
console.log(hex, '-->', data.value.toString())
this.destroy()
}
})
.on('end', function () {
console.log('(query finished)')
})
function sha256 (val) {
return crypto.createHash('sha256').update(val).digest()
}

15
example/insert.js

@ -0,0 +1,15 @@
const dht = require('../')
const crypto = require('crypto')
// Set ephemeral: true as we are not part of the network.
const node = dht({ ephemeral: true, bootstrap: ['localhost:10001'] })
const val = Buffer.from(process.argv[2])
node.update('values', sha256(val), val, function (err, res) {
if (err) throw err
console.log('Inserted', sha256(val).toString('hex'))
})
function sha256 (val) {
return crypto.createHash('sha256').update(val).digest()
}

37
example/network.js

@ -0,0 +1,37 @@
const dht = require('../')
const crypto = require('crypto')
// Let's create 100 dht nodes for our example.
for (var i = 0; i < 100; i++) createNode()
function createNode () {
const node = dht({
bootstrap: [
'localhost:10001'
]
})
const values = new Map()
node.command('values', {
// When we are the closest node and someone is sending us a "store" command
update (query, cb) {
if (!query.value) return cb()
// Use the hash of the value as the key
const key = sha256(query.value).toString('hex')
values.set(key, query.value)
console.log('Storing', key, '-->', query.value.toString())
cb()
},
// When someone is querying for a "lookup" command
query (query, cb) {
const value = values.get(query.target.toString('hex'))
cb(null, value)
}
})
}
function sha256 (val) {
return crypto.createHash('sha256').update(val).digest()
}
Loading…
Cancel
Save