Now that we've wrapped some files in a directory in our IPFS node, let's learn how we can check its contents. If you use the command line frequently, you're familiar with the ls command. IPFS offers a similar ls method to list the contents of a directory. However, as with the cat method we saw earlier, ls will actually look for the requested directory on your own node first, then search the broader network if needed. Because of the way cryptographic hashing works, two directories with identical CIDs are guaranteed to have identical contents, regardless of which peers are hosting them.
You can call the ls method like so:
ipfs.ls(ipfsPath)
The ipfsPath argument can take many formats, the simplest of which is a CID. (Remember, that's the same string value we saw returned to us as cid when we used the add or addAll method.) For example:
ipfs.ls("Qmeybqr2GaiUyGSRWX3dhS2Qz6VTVBXzBiYiFcKpYFJ7tH")
You can explore other ipfsPath formatting options in the ls documentation for the Regular Files API.
Because the 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.ls('/catPics')) {
result.push(resultPart)
}
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(ipfs.ls('/catPics'))
The result variable is now an array of objects, one for each file or directory found, structured like so:
{
"cid": Object,
"path": String,
"name": String,
"depth": Number,
"size": Number,
"type": String // can be "file" or "directory",
"mode": Number
}
Note that there's a different ls method in the MFS API (called as ipfs.files.ls() rather than ipfs.ls) with slightly different properties, which you can learn more about in our MFS tutorial.
Use ls to list the contents of the directory you created in the previous challenge.
Hint: The CID of the directory you created in the previous challenge has been stored for you in the directoryCID variable in the starter code below. Because the last element in the results returned by the addAll method is always the wrapping directory, our code finds that last element and saves its cid value, or CID.
Feeling stuck? We'd love to hear what's confusing so we can improve this lesson. Please share your questions and feedback.