Node 14開始,開始支持ES module語法。
JSON模塊工作在Node.js版本>=17.1中,也可以使用--experimental-json-modules標誌啓用Experimental JSON模塊
/*
Experimental JSON import in Node.js
$ node index.mjs
*/
// An import assertion in a static import
import info from `./package.json` assert { type: `json` };
// An import assertion in a dynamic import
const { default: info } = await import("./package.json", {
assert: {
type: "json",
},
});
我已經習慣在node.js使用require導入json,例如const data = require('./some-file.json'),上面的寫法無疑讓人感到沮喪。
如果你還不想使用這個實驗性的功能,這篇文章解釋了在ES模塊中處理JSON的方法。
1. 手動讀取和解析JSON文件
其實就是使用fs模塊讀取文件,然後再用JSON.parse解析。
import { readFile } from 'fs/promises';
const json = JSON.parse(
await readFile(
new URL('./some-file.json', import.meta.url)
)
);
2. 利用CommonJS的require函數來加載JSON文件(推薦)
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const data = require("./data.json");
createRequire允許你構造一個CommonJS require函數來使用CommonJS的典型功能,例如在Node.js的EcmaScript模塊中讀取JSON。
總結
import assertions無疑是未來ES modules導入json的最佳選擇,但可惜它目前依然是實驗性功能。至於介紹的2種替代方案,其實都不是最佳方案,但不影響你解決問題。
參考文章
- 厲害了,ECMAScript 新提案:JSON模塊
- How to import JSON files in ES modules (Node.js)