-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmock-server.js
More file actions
63 lines (59 loc) · 2.06 KB
/
mock-server.js
File metadata and controls
63 lines (59 loc) · 2.06 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
var peernet = require("peer-network")
var network = peernet()
var server = network.createServer()
var Readable = require("stream").Readable
var fs = require("fs")
function connect(name) {
console.log("starting server at " + name + "..")
server.listen("hyperdungeon") // listen on a name
server.on("listening", function() {
console.log("ready for connections")
})
// when someone connects, we receive their feed key. if they are joining for the first time we add them to the end of
// the feed list and then pass them the entire list
// they then use that list to propagate their hyperdb instance
server.on("connection", function (stream) {
console.log("new connection")
stream.on("data", function (data) {
console.log("received:", data.toString())
var peerKey = data.toString()
if (feeds.indexOf(peerKey) < 0) { // new peer connected, add them to our feeds
feeds.push(peerKey)
console.log(feeds)
fs.writeFile("./feeds.json", JSON.stringify(feeds), function(err) {
if (err) { console.log(err) }
})
}
var readStream = new Readable()
readStream.push(JSON.stringify(feeds))
readStream.push(null) // signals end of the read stream
readStream.pipe(stream) // reply
})
})
server.on("error", function(err) {
console.log(err)
})
}
var feeds = []
function start(name, key) {
return new Promise(function(resolve, reject) {
fs.readFile("./feeds.json", function(err, data) {
if (!err) {
feeds = JSON.parse(data)
} else {
feeds.push(key) // add the first key i.e. our key to feeds
}
resolve(feeds)
connect(name)
})
})
}
module.exports = start
module.exports.connect = function(name) {
fs.readFile("./feeds.json", function(err, data) {
if (!err) {
feeds = JSON.parse(data)
}
connect(name)
})
}