Node.js v17.1.0 及以上版本 原生支持 import json
。如果你的 Node.js 版本较低,需要额外的配置或使用 fs
读取 JSON 文件。
1. Node.js v17.1.0+
从 JSON 文件中导入数据(原生支持)
如果你的 Node.js 版本 >= 17.1.0 ,可以直接使用 import
方式加载 JSON 文件:
python
import data from './data.json' assert { type: 'json' };
console.log(data);
注意:
- 必须使用
assert { type: 'json' }
,否则会报错。 - 你的
package.json
需要"type": "module"
,或者以.mjs
结尾的文件。
2. Node.js v16.14.0+(实验性支持)
- 在 Node.js 16.14.0 及以上 ,可以使用
import
但需要--experimental-json-modules
选项:
css
node --experimental-json-modules index.mjs
代码示例:
python
import data from './data.json' assert { type: 'json' };
console.log(data);
⚠️ 3. 低版本(Node.js <16) 或 CommonJS 方式
如果你的 Node.js 版本 低于 16 ,或者你的项目使用的是 CommonJS (require()
),可以用 fs.readFileSync
读取 JSON:
ini
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('./data.json', 'utf8'));
console.log(data);
或者直接 require()
(适用于 Node.js 12+ ):
ini
const data = require('./data.json');
console.log(data);
** 总结**
Node.js 版本 | 方式 | 代码示例 |
---|---|---|
v17.1.0+ | 原生支持 import |
import data from './data.json' assert { type: 'json' }; |
v16.14.0+ | 实验性支持 | 需要 --experimental-json-modules |
低于 v16 | require() 或 fs 读取 |
const data = require('./data.json'); |