Mutable File System | Lesson 5 of 11

View the contents of a directory

When we add a file to MFS using files.write, there's no value returned by the method, but we can still check to ensure everything worked as expected.

In the Mutable File System, we can inspect directories using the method. It should feel very familiar if you've ever used the command line to list the contents of directories on your computer.

The method looks like this:[path], [options])

The method will default to listing the contents of your root directory ( / ), or you can choose to specify a specific path (directory) you'd like to inspect, such as /catPics, produces an array of objects, one for each file or directory contained in the directory you're inspecting, with the following properties:

  • name: the file's name
  • type: the object's type (0 - file or 1 - directory)
  • size: the size of the file in bytes
  • cid: the Content Identifier (CID) that identifies your file in IPFS
  • mode: the UnixFS mode as a Number
  • mtime: an object with numeric secs and nsecs properties

If we wanted to inspect the contents of a /catPics directory, we could do it like this:'/catPics')

Because the method returns an Async Iterable, you can only iterate over the values, one by one. If you need to return all the values, you can save each one into an array and then return the array.

To iterate over all the values, we can use a for await...of loop:

const result = []

for await (const resultPart of'/catPics')) {

return result

To make things easier, we can use the it-all package that does this automatically:

// the all function comes from the it-all package
// and is made globally available (just like ipfs) in our code challenges

const result = await all('/catPics'))

Try it!

Let's see in action! List the contents of your root directory ( / ).

Note: We've already included the code for adding your files to MFS, so you can focus on listing the contents of your directory.

Hint: Don't forget that returns an Async Iterable, so you'll need to either use the for await...of loop or the all function to return the result.

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.