In review so far we know how to:
There is a major gap in our code though if we'd like to make a chat program: with hypercore, there can only be one writer!
Well, what if each user had their own hypercore? Then we could view their contents together to see all of the chat history as other people are writing.
This was the motivation behind multifeed, a module that lets you operate on a set of hypercores, and create a replication stream, in the same way that you replicated hypercores in the last exercise.
Make a copy of single-chat.js
called multichat.js
, and replace usage of hypercore
with multifeed
. Here is how to create a multifeed, a new writer, and write to that feed:
var hypercore = require('hypercore')
var multifeed = require('multifeed')
var multi = multifeed(hypercore, './multichat', {valueEncoding:'json'})
multi.writer('local', function (err, feed) {
// 'feed' is a hypercore, just like before
// except now we can manage many of them together!
feed.append({
type: 'chat-message',
nickname: 'cat-lover',
text: 'hello world',
timestamp: '2018-11-05T14:26:000Z' // new Date().toISOString()
}, function (err, seq) {
if (err) throw err
console.log('Data was appended as entry #' + seq)
})
})
You can look at the previous solution converted to multifeed to start from.
multi.replicate
instead of the old feed.replcate
: multifeed will handle replicating all feeds for you.swarm.join('foobar-123')
node multichat.js
in two separate windows, each process must be using a different database. A good trick is to do something like this during multifeed creation:var suffix = process.argv[2]
var multi = multifeed(hypercore, './multichat-' + suffix, {valueEncoding:'json'})
This way, you can run node multichat.js 1
in one window, and node multichat.js 2
in the other window. If you try to run two processes that open the same multifeed database, things won't work!
multichat
, because hypercore and multifeed databases are not compatible.writer(name, cb)
that lets you create a new hypercore inside the multifeed.Once you solve this exercise continue to exercise 9