JSON File Persistence
Using JSON files as a simple data store — read, update, and atomic write patterns
Skills taught: node.json-read-write, node.atomic-write, node.json-persistence, node.data-patterns
Reading and writing JSON data
const fs = require('fs').promises;
const path = require('path');
const DATA_FILE = path.join(__dirname, 'users.json');
// ── Read ──
async function readUsers() {
try {
const raw = await fs.readFile(DATA_FILE, 'utf8');
return JSON.parse(raw);
} catch (err) {
if (err.code === 'ENOENT') return []; // file doesn't exist yet
throw err;
}
}
// ── Write (atomic) ──
async function writeUsers(users) {
const json = JSON.stringify(users, null, 2);
const temp = DATA_FILE + '.tmp';
await fs.writeFile(temp, json, 'utf8');
await fs.rename(temp, DATA_FILE); // atomic replace
}
// ── CRUD operations ──
async function addUser(user) {
const users = await readUsers();
user.id = users.length > 0 ? Math.max(...users.map(u => u.id)) + 1 : 1;
users.push(user);
await writeUsers(users);
return user;
}
async function updateUser(id, updates) {
const users = await readUsers();
const idx = users.findIndex(u => u.id === id);
if (idx === -1) throw new Error(`User ${id} not found`);
users[idx] = { ...users[idx], ...updates };
await writeUsers(users);
return users[idx];
}
async function deleteUser(id) {
const users = await readUsers();
const next = users.filter(u => u.id !== id);
if (next.length === users.length) throw new Error(`User ${id} not found`);
await writeUsers(next);
}
// Usage
(async () => {
const u1 = await addUser({ name: 'Alice', email: 'alice@example.com' });
const u2 = await addUser({ name: 'Bob', email: 'bob@example.com' });
console.log('Created:', await readUsers());
await updateUser(u1.id, { email: 'alice@newdomain.com' });
console.log('Updated Alice:', (await readUsers()).find(u => u.id === u1.id));
await deleteUser(u2.id);
console.log('After delete:', await readUsers());
})();
Frequently Asked Questions
When should I switch from JSON files to a real database?
Switch when: (1) you have concurrent writers (multiple requests at the same time) — JSON files have race conditions. (2) Your data grows past a few thousand records — no indexing, full scan on every read. (3) You need queries, filtering, or joins. SQLite (via better-sqlite3 or Bun's built-in) is a great step up — file-based like JSON but with full SQL, transactions, and indexes. Add PostgreSQL or MySQL when you need multi-server access.