To read a JSON file into server memory in Node.js, you can use the built-in fs (File System) module. Here's how you can do it:
Example:
const fs = require('fs');
// Asynchronous method to read JSON file
fs.readFile('path/to/your/file.json', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
const jsonData = JSON.parse(data); // Parse the JSON data
console.log(jsonData); // Log the JSON data to console
});
// Synchronous method to read JSON file
try {
const data = fs.readFileSync('path/to/your/file.json', 'utf8');
const jsonData = JSON.parse(data);
console.log(jsonData);
} catch (err) {
console.error('Error reading file:', err);
}