Every Node.js developer eventually comes across the necessity of reading JSON files. In this tutorial, we'll explore three easy ways to accomplish this.
require()
const jsonData = require('./data.json');
console.log(jsonData);
In this example, data.json
is your JSON file, and Node.js reads, parses, and returns the JSON object, which we store in the jsonData
variable.
fs
and JSON.parse()
const fs = require('fs');
fs.readFile('./data.json', 'utf8', (err, jsonString) => {
if (err) {
console.log("Error reading file from disk:", err);
return;
}
try {
const jsonData = JSON.parse(jsonString);
console.log(jsonData);
} catch(err) {
console.log('Error parsing JSON string:', err);
}
});
Here, we use the fs.readFile()
function to read the file content, then JSON.parse()
to convert it into a JavaScript object.
import jsonData from './data.json' assert { type: 'json' };
console.log(jsonData);
In this example, jsonData
will be the parsed JSON object from the data.json
file.
Each of these methods comes with its own strengths, and the best one to use depends on your specific needs.
require()
cache could be the reason. Node.js caches the result of require()
calls. If you want to re-read the file, you might need to delete the cache entry using delete require.cache[require.resolve('./data.json')]
.axios
or node-fetch
to fetch JSON from an external URL.Whether you choose to use require()
, fs
and JSON.parse()
, or ES modules to read JSON files will depend on your use case. Consider the needs of your application and pick the method that suits you best!
CloneCoding
Innovation Starts with a Single Line of Code!