ECMAScript模塊中node如何加載json文件》下面本篇文章就來給大家介紹一下nodejs在ECMAScript 模塊中加載json文件的方法,希望對(duì)大家有所幫助!
看完這篇文章,你將學(xué)到:
1、nodejs 如何加載、解析json文件
2、fs 模塊如何讀取json文件
3、學(xué)到import.meta.url
3、學(xué)到new URL()
4、學(xué)到load-json-file庫(kù)
眾所周知,如果是在CommonJS模塊
中加載json
文件,只需通過require()
函數(shù)直接加載即可,即能得到json
對(duì)象。
但是在ECMAScript模塊
中直接加載json文件,會(huì)報(bào)錯(cuò),報(bào)錯(cuò)如下:
首先,先啟用
ESM
模式,其實(shí)官方文檔(http://nodejs.cn/api/esm.html#introduction)中也有說明:Node.js 默認(rèn)將 JavaScript 代碼視為 CommonJS 模塊。 作者可以通過
.mjs
文件擴(kuò)展名、package.json
"type"
字段、或--input-type
標(biāo)志告訴 Node.js 將 JavaScript 代碼視為 ECMAScript 模塊
那怎么才能在ECMAScript模塊
加載json
文件呢?其實(shí)是有兩種方案的:
假設(shè)現(xiàn)在有一個(gè)json文件:test.json
文件內(nèi)容如下:
{ "name": "project" }
接下來,在index.js
中引入test.json
:
一、 通過 fs
文件系統(tǒng)讀取 json
文件
import { readFile } from "fs/promises"; // 以promise的方式引入 readFile API const json = JSON.parse( await readFile(new URL('./test.json', import.meta.url)) ) console.log('[json1]:', json); // 輸出: { "name": "project" }
解釋:
await
: 根據(jù) ECMAScript 頂層 await
提案,await
關(guān)鍵字可用于模塊內(nèi)的頂層(異步函數(shù)之外);
import.meta.url
:nodejs
中返回模塊在本地的file://
協(xié)議的絕對(duì)路徑,例如:file://home/user/main.js
, 如果模塊中還有另外一個(gè)文件test.js
,那么test.js
的路徑就是new URL('test.js', import.meta.url)
;
new URL
: 生成file:
協(xié)議的對(duì)象(對(duì)于大多數(shù) fs
模塊函數(shù),path
或 filename
參數(shù)可以作為使用 file:
協(xié)議的對(duì)象傳入)。
二、 通過nodejs
內(nèi)置module
模塊的createRequire
方法實(shí)現(xiàn)
import { createRequire } from "module"; const require = createRequire(import.meta.url); const json = require('./test.json'); console.log('[json2]:', json); // 輸出: { "name": "project" }
這種方法是根據(jù)nodejs
提供的createRequire
方法實(shí)現(xiàn)。
三、 24行源碼的第三方庫(kù) load-json-file
load-json-file 是我在npm網(wǎng)站無意間發(fā)現(xiàn)的,源碼只有僅僅24行,如下:
import {readFileSync, promises as fs} from 'node:fs'; const {readFile} = fs; const parse = (buffer, {beforeParse, reviver} = {}) => { // Unlike `buffer.toString()` and `fs.readFile(path, 'utf8')`, `TextDecoder`` will remove BOM. // 這里對(duì)buffer進(jìn)行轉(zhuǎn)義,沒有用`buffer.toString()`和`fs.readFile(path, 'utf8')`,是因?yàn)閌new TextDecoder().decode(buffer)`這種方式可以刪除字節(jié)順序標(biāo)記(BOM) // 解碼 buffer 并返回字符串 let data = new TextDecoder().decode(buffer); // 在parse解析之前對(duì)字符串進(jìn)行處理 if (typeof beforeParse === 'function') { data = beforeParse(data); } return JSON.parse(data, reviver); }; // 導(dǎo)出異步方法 export async function loadJsonFile(filePath, options) { // 如果未指定編碼,則返回原始緩沖區(qū)。 const buffer = await readFile(filePath); return parse(buffer, options); } // 導(dǎo)出同步方法 export function loadJsonFileSync(filePath, options) { // 如果未指定編碼,則返回原始緩沖區(qū)。 const buffer = readFileSync(filePath); return parse(buffer, options); }
load-json-file 源碼 整體而言相對(duì)比較簡(jiǎn)單,但是也有很多可以學(xué)習(xí)深挖的學(xué)習(xí)的知識(shí)點(diǎn)。