如何使用Javascript从IPFS读取JSON文本并转换为可用对象
IPFS读取JSON文件并转换为对象的解决方案
实现代码(无需额外安装依赖)
const { create } = require('ipfs-http-client'); async function fetchJsonFromIpfs(cid) { const client = await create('https://ipfs.infura.io:5001/api/v0'); const chunks = []; let totalLength = 0; // 收集所有二进制块 for await (const chunk of client.cat(cid)) { chunks.push(chunk); totalLength += chunk.length; } // 拼接为完整二进制数组 const fullBuffer = new Uint8Array(totalLength); let offset = 0; for (const chunk of chunks) { fullBuffer.set(chunk, offset); offset += chunk.length; } // 解码为字符串后转JSON对象 const contentStr = new TextDecoder('utf-8').decode(fullBuffer); return JSON.parse(contentStr); } // 调用示例 fetchJsonFromIpfs('QmPChd2hVbrJ6bfo3WBcTW4iZnpHm8TEzWkLHmLpXhF68A') .then(jsonResult => console.log(jsonResult)) .catch(err => console.error('读取失败', err));
简化写法(使用ipfs-http-client自带依赖)
ipfs-http-client自身依赖uint8arrays包,无需额外安装即可直接调用拼接方法:
const { create } = require('ipfs-http-client'); const concat = require('uint8arrays/concat'); async function fetchJsonFromIpfs(cid) { const client = await create('https://ipfs.infura.io:5001/api/v0'); const chunks = []; for await (const chunk of client.cat(cid)) { chunks.push(chunk); } const contentStr = new TextDecoder('utf-8').decode(concat(chunks)); return JSON.parse(contentStr); }
说明
你之前输出的数字是Uint8Array格式二进制数据的字节值,直接打印时默认会展示每个字节的十进制数值,你提供的输出结果转码后为字符串Hello, <YOUR NAME HERE>,与对应CID的存储内容一致。
内容的提问来源于stack exchange,提问作者Maxi
相关产品推荐
相关产品推荐

