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

使用ipfs-http-client连接Infura存数据时遇ERR_PACKAGE_PATH_NOT_EXPORTED错误

问题

我正在开发一个将数据存储到IPFS的项目,使用Node.js和Infura实现。但运行代码时出现如下错误:

D:\BlockChain\IPFS>node app.js
node:internal/modules/cjs/loader:585
      throw e;
      ^
"Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in D:\BlockChain\IPFS\node_modules\ipfs-http-client\package.json"

我的代码如下:

const { create } = require("ipfs-http-client");
const fs = require("fs");
// Login to infura.io and go to IPFS to create a project, after creating the project you will get the INFURA_SECRET_KEY and INFURA_ID set them here.
const INFURA_ID = "";// made empty for security purpose
const INFURA_SECRET_KEY = "";// made empty for security purpose
const auth =
  "Basic " +
  Buffer.from(INFURA_ID + ":" + INFURA_SECRET_KEY).toString("base64");
async function ipfsClient() {
  const ipfs = await create({
    host: "ipfs.infura.io",
    port: 5001,
    protocol: "https",
    headers: {
      authorization: auth, // infura auth credentails
    },
  });
  return ipfs;
}

async function saveText() {
  let ipfs = await ipfsClient();

  let result = await ipfs.add(`welcome ${new Date()}`);
  console.log(result);
}
saveText();

我已尝试升级Node.js版本、执行npm update、npm audit fix --force、删除package-lock.json等多种方法,但均无效。请问我是否遗漏了什么?

解决方案

这个错误的核心原因是ipfs-http-client v50及以上版本完全切换为ES模块,同时调整了导出结构,你的CommonJS语法(require)无法正确加载新版本模块。可以通过两种方式解决:

方法1:切换为ES模块写法

  1. 要么将代码文件的后缀改为.mjs,要么在项目根目录的package.json中添加配置:"type": "module"。
  2. 修改导入语句为ES模块格式:
import { create } from 'ipfs-http-client';

其余代码逻辑无需改动,直接运行即可。

方法2:降级到兼容CommonJS的旧版本

如果不想修改代码结构,直接安装ipfs-http-client v49.x版本:

npm uninstall ipfs-http-client
npm install ipfs-http-client@49.0.4

安装完成后,原有代码可以正常运行。

额外注意事项:

  • 若选择降级方案,确保Node.js版本不低于16.x;若用ES模块方案,建议Node.js版本不低于18.x。
  • 避免在同一项目中混用ES模块和CommonJS写法,防止出现模块加载冲突。

内容的提问来源于stack exchange,提问作者Asir Shahriar Roudra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:53:15