Skip to content

Latest commit

 

History

History
26 lines (18 loc) · 1.88 KB

File metadata and controls

26 lines (18 loc) · 1.88 KB
title type
Read the contents of a file
file-upload

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:

ipfs.files.read(path, [options])

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

The 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 new TextDecoder().encode(buffer). 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(ipfs.files.read('/directory/some-file.txt'))  // a buffer
let contents = new TextDecoder().decode(bufferedContents) // 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.