Unable to Download File Using ipfs.cat from Private IPFS Cluster (Error: "this dag node is a directory") – How to Handle CIDs for Directories?

Hello everyone,

I’m currently working on a backend service using Node.js to interact with my private IPFS cluster. The goal is to download a file by passing it’s CID. However, when I use the ipfs.cat method, I’m encountering the following error:
Error: this dag node is a directory

From what I understand, the error occurs because the CID I’m trying to fetch points to a directory rather than an individual file. However, I’m certain that I’m passing the CID of specific files only. I’m looking for the correct approach to handle this situation where the CID references a directory, but I still need to download a particular file from it.

What I’ve Tried

I’m using the ipfs.cat(cid) method, as shown below, to download the file:

let fileChunks = [];
    for await (const chunk of ipfs.cat(cid)) {
      fileChunks.push(chunk);
    }
    const fileBuffer = Buffer.concat(fileChunks)
    return fileBuffer.toString('base64');

But this approach fails when the CID corresponds to a directory. I haven’t been able to find a way to navigate through the directory to download the specific file.

My Requirements

  1. How can I download the specific file contents through it’s CID ?
  2. How can I correctly fetch files when the CID refers to a directory?
  3. Is there a different method I should use for directories to retrieve the file contents?
  4. Is there any way to recursively traverse a directory DAG and download a specific file from it?
  5. If a CID points to a directory, what are the best practices to fetch the content from the directory (either list files, retrieve them, etc.)?

My Environment

  • Node.js version: 20.17.0
  • IPFS client version( ipfs-http-client ): ^53.0.1
  • IPFS Cluster: Private
  • OS: Linux

I know that the CID structure for directories in IPFS is different. Still, I couldn’t find clear examples or documentation explaining how to retrieve files within a directory DAG node in this context. If anyone can provide code examples or point me to the relevant documentation, that would be extremely helpful!

Thanks in advance for your help!