You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Helia库中连接本地节点、上传文件并修改元数据?

使用Helia替代ipfs-http-client实现IPFS操作

依赖安装

首先安装Helia核心及文件操作相关包:

npm install @helia/http @helia/unixfs

连接本地IPFS节点并上传元数据

以下代码对应你原ipfs-http-client的功能,实现连接本地IPFS Desktop节点、上传NFT元数据:

import { createHeliaHTTP } from '@helia/http'
import { unixfs } from '@helia/unixfs'

async function run() {
  // 连接本地IPFS Desktop的HTTP API(默认端口5001)
  const helia = await createHeliaHTTP({
    url: 'http://localhost:5001/api/v0'
  })

  // 初始化UnixFS操作工具,处理IPFS文件系统交互
  const fs = unixfs(helia)

  // 构建NFT元数据结构
  const metadata = {
    name: "My First NFT",
    attributes: [
      {
        "trait_type": "Peace",
        "value": "10" 
      },
      {
        "trait_type": "Love",
        "value": "100"
      },
      {
        "trait_type": "Web3",
        "value": "1000"
      }
    ],
    image: "https://ipfs.io/ipfs/QmQ2wnwaFJ1w42UTywTWpM8RgiqrWwKFR6AMrpyiHPgi3p",
    description: "So much PLW3!"
  }

  // 将元数据转为字节数组并上传到IPFS
  const metadataBytes = new TextEncoder().encode(JSON.stringify(metadata))
  const cid = await fs.addBytes(metadataBytes)

  console.log(`元数据上传完成,CID: ${cid.toString()}`)

  // 验证本地节点状态(可选)
  const nodeVersion = await helia.api.version()
  console.log(`本地IPFS节点版本: ${nodeVersion.version}`)

  // 关闭Helia连接
  await helia.stop()
}

run()

额外功能实现

上传本地图片

如果需要上传本地图片文件,使用fs.addFile方法:

// 上传本地图片文件
const imageCid = await fs.addFile('./path/to/your/image.png')
console.log(`图片上传完成,CID: ${imageCid.toString()}`)

// 可将图片CID更新到元数据的image字段,格式为 `ipfs://${imageCid.toString()}`

修改元数据

IPFS内容具有不可变性,无法直接修改已上传的元数据。需按以下步骤操作:

  1. 修改元数据对象的字段(例如调整attributes值或替换图片CID)
  2. 重复上述上传步骤,生成新的CID
  3. 使用新CID访问更新后的元数据

内容的提问来源于stack exchange,提问作者codingJourneyFromUnemployment

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 17:55:03