| title | View the contents of a directory |
|---|---|
| type | file-upload |
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 files.ls
method. It should feel very familiar if you've ever used the command line to list
the contents of directories on your computer.
The files.ls method looks like this:
ipfs.files.ls([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,
files.ls 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 nametype: the object's type (0- file or1- directory)size: the size of the file in bytescid: the Content Identifier (CID) that identifies your file in IPFSmode: the UnixFS mode as a Numbermtime: a two-element structure (secs,nsecs) representing the modification time in seconds relative to the Unix epoch1970-01-01T00:00:00Z
If we wanted to inspect the contents of a /catPics
directory, we could do it like this:
ipfs.files.ls('/catPics')Because the files.ls 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 ipfs.files.ls('/catPics')) {
result.push(resultPart)
}
return resultTo 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(ipfs.files.ls('/catPics'))