3 - Storing and retrieving data

As mentioned previously, Hypercore is an append-only data structure. Let's try to use it to store some data and read it out again.

What if we wanted to build a peer-to-peer chat app? We might want to know the text of the message, message type, nickname, and perhaps a timestamp. Let's store messages in a specific format – using JSON – so we can identify them as chat messages, as shown here:

// Save this file as single-chat.js

const hypercore = require('hypercore')
const feed = hypercore('./single-chat-feed', {
  valueEncoding: 'json'
})

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)
})

Exercise

Try running the above code a couple of times. You should see the entry sequence number increase each time. The entry sequence number (or seq) is the "key" to this data entry and you can use it to retrieve the data again using the feed.get api.

Try reading out the first entry (0) using the feed.get api and console.log() it.

It should return a JSON object similar to the one you added.

Once you solve this exercise continue to exercise 4