Browse Source

add back examples

session-estimator
Mathias Buus 4 years ago
parent
commit
b9745121f9
  1. 6
      examples/bootstrap.js
  2. 25
      examples/find.js
  3. 19
      examples/insert.js
  4. 36
      examples/network.js

6
examples/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 = new DHT({ ephemeral: true })
bootstrap.bind(10001)

25
examples/find.js

@ -0,0 +1,25 @@
const DHT = require('../')
const crypto = require('crypto')
const hex = process.argv[2]
const node = new DHT({ ephemeral: true, bootstrap: ['localhost:10001'] })
run()
async function run () {
const q = node.query(Buffer.from(hex, 'hex'), 'values')
for await (const data of q) {
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())
break
}
}
console.log('(query finished)')
}
function sha256 (val) {
return crypto.createHash('sha256').update(val).digest()
}

19
examples/insert.js

@ -0,0 +1,19 @@
const DHT = require('../')
const crypto = require('crypto')
// Set ephemeral: true as we are not part of the network.
const node = new DHT({ ephemeral: true, bootstrap: ['localhost:10001'] })
const val = Buffer.from(process.argv[2])
run()
async function run () {
const q = node.query(sha256(val), 'values')
await q.finished()
await q.commit('values', val)
console.log('Inserted', sha256(val).toString('hex'))
}
function sha256 (val) {
return crypto.createHash('sha256').update(val).digest()
}

36
examples/network.js

@ -0,0 +1,36 @@
const DHT = require('../')
const crypto = require('crypto')
// Let's create 100 dht nodes for our example.
const swarm = []
for (let i = 0; i < 100; i++) swarm[i] = createNode()
function createNode () {
const node = new DHT({
bootstrap: [
'localhost:10001'
]
})
const values = new Map()
node.on('request', function (req) {
if (req.command === 'values') {
if (req.update) {
const key = sha256(req.value).toString('hex')
values.set(key, req.value)
console.log('Storing', key, '-->', req.value.toString())
return req.reply(null)
}
const value = values.get(req.target.toString('hex'))
req.reply(value)
}
})
return node
}
function sha256 (val) {
return crypto.createHash('sha256').update(val).digest()
}
Loading…
Cancel
Save