How to read and write a JSON file in Node.js
Short answer
Read the file as a string and parse it with JSON.parse():
import { readFile, writeFile } from 'node:fs/promises';
await writeFile('settings.json', '{"theme":"dark","fontSize":14}');
const settings = JSON.parse(await readFile('settings.json', 'utf8'));
console.log(settings.theme, settings.fontSize);Output:
dark 14Writing
JSON.stringify() with an indent of 2 makes the file readable:
import { readFile, writeFile } from 'node:fs/promises';
const settings = { theme: 'light', languages: ['en', 'de'] };
await writeFile('settings.json', JSON.stringify(settings, null, 2));
console.log(await readFile('settings.json', 'utf8'));Output:
{
"theme": "light",
"languages": [
"en",
"de"
]
}Update a value
Read, change and write back:
import { readFile, writeFile } from 'node:fs/promises';
await writeFile('counter.json', '{"visits":41}');
const data = JSON.parse(await readFile('counter.json', 'utf8'));
data.visits++;
await writeFile('counter.json', JSON.stringify(data));
console.log(await readFile('counter.json', 'utf8'));Output:
{"visits":42}Common mistake
A damaged file makes JSON.parse() throw. Catch the error and use default values:
import { readFile, writeFile } from 'node:fs/promises';
await writeFile('broken.json', '{"theme": "dark",}');
let settings;
try {
settings = JSON.parse(await readFile('broken.json', 'utf8'));
} catch (error) {
console.log('Broken file:', error.name);
settings = { theme: 'light' };
}
console.log(settings.theme);Output:
Broken file: SyntaxError
lightFunctions used in this recipe
- JSON.parse — Parses a JSON string and returns the value.
- JSON.stringify — Converts a value to a JSON string.