Read a JSON text from IPFS with Javascript

Viewed 821

I did not find yet anywhere a working solution for this simple thing: I want to read the content of an IPFS JSON file that I previously uploaded.

const chunks = [];
const client = await create('https://ipfs.infura.io:5001/api/v0');

for await (const chunk of client.cat(
  'QmPChd2hVbrJ6bfo3WBcTW4iZnpHm8TEzWkLHmLpXhF68A',
)) {
  chunks.push(chunk);
}

console.log(chunks);

Output: 72,101,108,108,111,44,32,60,89,79,85,82,32,78,65,77,69,32,72,69,82,69,62

I tried this snippet that I found in various formats on the internet. But it gives me a Uint8Array that consists of numbers. Yet I was not able to convert chunks to a JSON object as I need it. Can somebody please provide a snippet for this, please?

I am using

"ipfs-http-client": "^53.0.1"

Thanks in advance!

1 Answers

You'll need to convert the Uint8Array buffer to a string first:

const result = JSON.parse(chunk.toString());
Related