Q1. How do you read a JSON file in Node.js?
Read the file with fs.readFile(), then parse with JSON.parse(). Example:
fs.readFile('data.json', 'utf8', (err, data) => {
if (err) throw err;
const obj = JSON.parse(data);
console.log(obj);
});
Alternatively, use require() for JSON files:
const data = require('./data.json')
- but this caches the result.Q2. How do you write a JSON file?
Convert object to JSON string with JSON.stringify(), then write with fs.writeFile(). Example:
const obj = { name: 'John', age: 30 };
const json = JSON.stringify(obj, null, 2); // pretty print
fs.writeFile('output.json', json, (err) => {
// ...
});
The null, 2 arguments add indentation for readability.Q3. How do you update a JSON file?
Read the file, parse, modify the object, then write back. Example:
fs.readFile('data.json', (err, data) => {
const obj = JSON.parse(data);
obj.newProp = 'value';
fs.writeFile('data.json', JSON.stringify(obj, null, 2), (err) => {
// ...
});
});
Be careful with concurrent writes - use file locking or a database for production.Q4. What are the advantages of using require() for JSON?
require('./file.json') automatically parses JSON and returns the object. It's synchronous and caches the result, so subsequent requires don't read the file again. This is convenient for configuration files that don't change during runtime. However, for dynamic JSON, use fs methods.
Q5. How do you handle JSON parsing errors?
Wrap JSON.parse() in try/catch. Example:
try {
const obj = JSON.parse(data);
} catch (err) {
if (err instanceof SyntaxError) {
console.error('Invalid JSON');
} else {
throw err;
}
}
This prevents your app from crashing due to malformed JSON files.