MFS has a
files.read method that allows you to display the contents of a file in a buffer. This allows us to easily read the contents of a
.txt file among others.
The method takes this format:
path provided is the path of the file to read, and it must point to a file rather than a directory.
files.read method returns an Async Iterable that iterates over the file's chunks of data, i.e. Buffers. In our case, we ultimately need to convert Buffers into strings using the method
toString(). However, the chunks of data within a single file need to be reassembled (concatenated) before the conversion. The
it-to-buffer package can iterate over all of the chunks and put them back together for us. (We've made this package available to you in our challenges as
// the toBuffer variable is globally available (just like ipfs) let bufferedContents = await toBuffer(ipfs.files.read('/directory/some-file.txt')) // a buffer let contents = bufferedContents.toString() // a string
When you're ready to try this in the real world, you should note that the above example can result in heavy memory usage, depending on the contents of the file being read. If you're working with large files and find this to be the case, you might want to skip using the
it-to-buffer package and instead process each chunk of data iteratively. The main reason IPFS now returns
Async Iterables is to provide a built-in option for dealing with potential performance issues.
In ProtoSchool tutorials, our code challenges use small files, so we can concatenate everything without worrying about performance.
We hid a secret message for you in that file you copied from IPFS as
files.read to save the content of the file (as a string) to the
secretMessage variable we've created for you below.
Hint: Remember that you'll need to convert the buffer returned by
files.read to a string.
Feeling stuck? We'd love to hear what's confusing so we can improve this lesson. Please share your questions and feedback.