Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to load json File by nodejs in ECMAScript Module

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "ECMAScript module nodejs how to load json files", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "ECMAScript module nodejs how to load json files" bar!

After reading this article, you will learn:

1. How nodejs loads and parses json files

2. How does the fs module read the json file

3. Learn import.meta.url

3. Learn new URL ()

4. Learn the load-json-file library

As we all know, if you load the json file in the CommonJS module, you only need to load it directly through the require () function, and you can get the json object.

However, if you load the json file directly into the ECMAScript module, an error will be reported as follows:

First of all, enable ESM mode first, which is also stated in the official documentation (http://nodejs.cn/api/esm.html#introduction):

By default, Node.js treats JavaScript code as a CommonJS module. The author can tell Node.js to treat the JavaScript code as an ECMAScript module through the .mjs file extension, the package.json "type" field, or the-- input-type flag

So how can I load the json file in the ECMAScript module? In fact, there are two options:

Suppose you now have a json file: test.json

The contents of the document are as follows:

{"name": "project"}

Next, introduce test.json into index.js:

1. Read the json file import {readFile} from "fs/promises" through the fs file system; / / introduce readFile APIconst json = JSON.parse (await readFile (new URL ('. / test.json', import.meta.url)) console.log ('[json1]:', json) by promise; / / output: {"name": "project"}

Explanation:

Await: according to the ECMAScript top-level await proposal, the await keyword can be used at the top level within the module (outside of asynchronous functions)

Import.meta.url:nodejs returns the absolute path of the module to the local file:// protocol, for example: file://home/user/main.js,. If there is another file test.js in the module, then the path to test.js is new URL ('test.js', import.meta.url).

New URL: the object that generates the file: protocol (for most fs module functions, the path or filename parameter can be passed as an object that uses the file: protocol).

2. Implement import {createRequire} from "module" through the createRequire method of nodejs's built-in module module; const require = createRequire (import.meta.url); const json = require ('. / test.json'); console.log ('[json2]:', json); / / output: {"name": "project"}

This method is implemented based on the createRequire method provided by nodejs.

Third-party library load-json-file with three or 24 lines of source code

I stumbled upon load-json-file on the npm website. The source code is only 24 lines, as follows:

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. / / buffer is escaped here, instead of `fs.readFile () `and `fs.readFile (path, 'utf8')`, because `new TextDecoder () .decode (buffer) `can delete the byte order mark (BOM) / / decode buffer and return the string let data = new TextDecoder () .decode (buffer) / / process the string before parse parsing if (typeof beforeParse = = 'function') {data = beforeParse (data);} return JSON.parse (data, reviver);}; / / Export the asynchronous method export async function loadJsonFile (filePath, options) {/ / return the original buffer if no encoding is specified. Const buffer = await readFile (filePath); return parse (buffer, options);} / Export synchronization method export function loadJsonFileSync (filePath, options) {/ / if no encoding is specified, the original buffer is returned. Const buffer = readFileSync (filePath); return parse (buffer, options);}

The load-json-file source code as a whole is relatively simple, but there are also many knowledge points that you can learn to dig deep into.

Thank you for reading, the above is the content of "how nodejs loads json files in the ECMAScript module". After the study of this article, I believe you have a deeper understanding of how nodejs loads json files in the ECMAScript module, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 265

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report