Mutable File System | Lesson 10 of 11

Read the contents of a file

MFS has a 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:, [options])

The path provided is the path of the file to read, and it must point to a file rather than a directory.

The 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 toBuffer.)

// the toBuffer variable is globally available (just like ipfs)

let bufferedContents = await toBuffer('/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.

Try it!

We hid a secret message for you in that file you copied from IPFS as success.txt. Use 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 to a string.

Step 1: Upload files
Step 2: Update code
View SolutionReplace with SolutionClear Default Code
Upload file(s) and update the code to complete the challenge.
You must upload a file before submitting.