Small apps and prototypes store data in JSON files on disk—simple but not concurrent-safe at scale. Learn read-modify-write patterns before reaching for MongoDB or PostgreSQL.
Read and write JSON
import { readFile, writeFile } from 'node:fs/promises';
async function loadDb(path) {
try {
return JSON.parse(await readFile(path, 'utf8'));
} catch (err) {
if (err.code === 'ENOENT') return { items: [] };
throw err;
}
}
async function saveDb(path, data) {
await writeFile(path, JSON.stringify(data, null, 2));
}
Limitations
Race conditions when two requests write simultaneously—use file locks, a database, or a queue for production. Good for CLI tools and learning.
Important interview questions and answers
- Q: When is JSON file storage OK?
A: Prototypes, single-user tools, config caches—not high-write multi-tenant APIs. - Q: Atomic writes?
A: Write to temp file then rename—reduces partial writes on crash.
Self-check
- What error code means file missing?
- Why pretty-print JSON with null, 2 in dev only?