Node.js使用ES6导入JSON文件报‘Cannot find package’错的解决方法
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 namedusers.json(scanning yournode_modulesfolder), not a local file. That's why it can't locate your JSON file! - The
fsmodule 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 yourpackage.jsonfile. This tells Node.js to treat.jsfiles as ES modules instead of CommonJS, which is required for theimportsyntax 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

