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

Node.js使用ES6导入JSON文件报‘Cannot find package’错的解决方法

Fixing "Cannot find package 'users.json'" When Importing JSON in Node.js ES Modules

Hey there! Let's break down why you're hitting this error and get that JSON import working with ES6 syntax properly.

First off, the core issue behind the "Cannot find package 'users.json'" error is how Node.js resolves ES module imports:

  • When you write import data from 'users.json', Node.js treats this as a request to load an npm package named users.json (scanning your node_modules folder), not a local file. That's why it can't locate your JSON file!
  • The fs module works because it uses standard file system path resolution—it looks directly for the file in your current directory if you don't specify an absolute path.

Here are the correct ways to import your JSON file with ES6 syntax:

1. Use Import Assertions (Official Standard Method)

This is the recommended approach for importing JSON in ES modules, supported in Node.js 16.14.0+, 17.1.0+, and all newer versions.

Step-by-Step Fix:

  • Correct the file path: Add ./ at the start of the path to tell Node.js it's a local file (not an npm package).
  • Add the import assertion: Explicitly declare that you're importing a JSON file with assert { type: 'json' }.

Your corrected code will look like this:

'use strict';
import data from './users.json' assert { type: 'json' };
console.log(data);

For Older Node.js Versions:

If you're running Node.js <16.14.0 or <17.1.0, you'll need to enable the experimental JSON modules flag when executing your script:

node --experimental-json-modules your-script.js

2. Double-Check Your ES Module Setup

Ensure your project is configured to use ES modules:

  • Add "type": "module" to your package.json file. This tells Node.js to treat .js files as ES modules instead of CommonJS, which is required for the import syntax to function correctly.

Alternative: fs + JSON.parse (ES Module-Friendly Version)

Since you mentioned the fs module works already, here's a cleaner async/await version for reference:

'use strict';
import { readFile } from 'fs/promises';

async function loadUserData() {
  const rawJson = await readFile('./users.json', 'utf8');
  const data = JSON.parse(rawJson);
  console.log(data);
}

loadUserData();

That should get your JSON importing smoothly with ES6 syntax!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:14:30