5 - Messages in Real Time

A necessary part of a chat program is, of course, the ability to see the chat messages written to it.

hypercore has a function called createReadStream that returns a Readable node stream of feed entries / messages, starting from sequence number (seq) zero, and counting up.

Streams are useful for reading data in real-time. Any time data is added to the database, you can detect these new entries and display them how you'd like to the user.

feed.createReadStream(options) has an option called {live: true}. If you set this, the stream will stay open and keep emitting new data as it is appended to the hypercore.

Exercise

Write code in single-chat.js that reads lines of input from the user, and uses createReadStream to write those messages back to the console as they are emitted from hypercore, e.g.

$ node single-chat.js
hello<ENTER>
<2018-11-05T14:26:000Z> cat-lover: hello

Tips

process.stdin.on('data', function (data) {
  feed.append({
    type: 'chat-message',
    nickname: 'cat-lover',
    text: data.toString().trim(),
    timestamp: new Date().toISOString()
  })
})
feed.createReadStream({ live: true })
  .on('data', function (data) {
    console.log(data)
  })

Once you solve this exercise continue to exercise 6