Regular Files API | Lesson 8 of 8

Get all of the files in a directory

Need to know more about an IPFS file or directory beyond just its contents? Whereas cat retrieves just the buffered content of a file, we can access additional metadata about a file or directory by calling the get method like so:

ipfs.get(ipfsPath)

The result is an array of objects, one per file or directory, with the following structure:

{
    cid: Object,
    name: String,
    path: String,
    depth: Number,
    size: Number,
    type: String, //can be "file" or "dir"
    content: Buffer, // only exists if the type === "file"
}

As with cat and ls, the get method will search for the requested file or directory on the IPFS network if it can't find it on your local node.

The use case for get versus cat or ls

Returning both metadata and content

The get method returns metadata for all files and subdirectories, as well as content for all files.

Notice that the data returned by get (as shown above) is structured almost identically to the result of the ls method, except that we now see contents returned (if the target is a file) in addition to metadata.

In the case of a file, get returns metadata in addition to the buffered content we could have retrieved using cat.

Just like ls, get will return an Async Iterable, so we still need to use the it-all package on its return value.

await all(ipfs.get(ipfsPath))

Returning directory contents recursively

Another very important distinction between get and these other methods is that, when run on a directory, it will retrieve contents recursively, meaning that the resulting array will contain an entry for the specified directory itself as well as every subdirectory and every file present inside the specified directory, even those inside of subdirectories.

By contrast, the ls method returns an array with metadata only for the top-level contents within the specified directory (whether files or subdirectories). It doesn't return an entry for the specified directory itself and it doesn't return entries for the contents of subdirectories.

The get method can:

  • Recursively retrieve every file and subdirectory in a directory
  • Tell us which entries are directories and which are files
  • Inform us of the size of a file
  • Pinpoint the depth of a file in the directory structure
  • and offer many other details

not yet startedTry it!

For this last challenge, we've created the following file structure in your IPFS node:

/
/shrug.txt
/smile.txt
/fun/
/fun/success.txt

The CID of the top-level directory is: "QmcmnUvVV31txDfAddgAaNcNKbrtC2rC9FvkJphNWyM7gy"

Use the get method to return data on all of the files and subdirectories contained in the top-level directory.

Hint: Be sure to return the array created by the get method.

View SolutionReplace with SolutionClear Default Code
Update the code to complete the challenge. Click Submit to check your answer.