Node.js is a very popular JavaScript runtime environment that is widely used for server-side application development. During the development of Node.js projects, reading JSON files is a very practical function. This article will introduce how to read JSON files in Node.js projects.
fs (file system) is a built-in core module of Node.js, providing an API for file operations. JSON files can be easily read using the fs module:
const fs = require('fs'); fs.readFile('data.json', 'utf-8', (err, data) => { if (err) { console.error(err); return; } const json = JSON.parse(data); console.log(json); });
The above code uses the readFile
method to read the content from the data.json
file and parse it In JSON format. If the read is successful, it will be printed to the console.
It should be noted that the readFile
method is an asynchronous method and needs to pass a callback function to process the read result. The first parameter in the callback function is the error object. If the reading fails, the error object will be returned. The second parameter is the read file content. If the reading is successful, the file content will be returned.
In Node.js, you can use the require
method to import a JSON file as a module:
const json = require('./data.json'); console.log(json);
The above code uses the require
method to import the data.json
file as a module. After importing, the json object can be used directly.
It should be noted that when using the require
method to import a JSON file, the file path needs to start with ./
or ../
, and The file name needs to end with .json
.
In addition to using the built-in fs module and require method to read JSON files, you can also use third-party modules to read JSON files, such as fs-extra
and jsonfile
modules.
fs-extra
module is an enhanced version of the fs module, providing a more convenient API, including APIs for reading and writing JSON files:
const fs = require('fs-extra'); fs.readJson('data.json', (err, json) => { if (err) { console.error(err); return; } console.log(json); });
# The ##jsonfile module also provides a similar API:
const jsonfile = require('jsonfile'); jsonfile.readFile('data.json', (err, json) => { if (err) { console.error(err); return; } console.log(json); });
fs-extra and
jsonfile modules in the project, which can be done using the npm command Installation:
npm install fs-extra jsonfile --save
The above is the detailed content of How to read JSON file in Node.js project. For more information, please follow other related articles on the PHP Chinese website!