Reading JSON files in Node.js is a common task in application development. Node.js provides built-in modules for working with files, making reading JSON files very easy and straightforward.
The 'fs' (file system) module in Node.js allows us to interact with the machine's file system. To read a JSON file, we first need to import the 'fs' module and then use the 'readFile' method. For example:
const fs = require('fs');
fs.readFile('file.json', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file', err);
return;
}
console.log('File content:', data);
});
Another common way to read a JSON file in Node.js is by using the 'require' function. This function is usually used to load modules, but it can also load JSON files directly. For example:
const file = require('./file.json');
console.log('File content:', file);
Jorge García
Fullstack developer