Reading and writing files with fs/promises
Before there is a database, there are files. Real backends read CSV exports from partners, JSON dumps from legacy systems, and config files at startup. Knowing how to read and write files cleanly is a foundational backend skill, even when the long-term home for the data is a database.
Because callbacks force you to nest. Read a file, parse it, validate it, write the result, and you end up with four levels of indentation and an error handling story that is hard to follow. fs/promises gives you the same operations but as promises, so you can use async/await and write the steps top to bottom.
import fs from 'fs/promises';
async function loadBooks(inputPath: string) {
const raw = await fs.readFile(inputPath, 'utf-8');
const parsed = JSON.parse(raw);
return parsed;
}
async function saveBooks(outputPath: string, books: unknown) {
const json = JSON.stringify(books, null, 2);
await fs.writeFile(outputPath, json, 'utf-8');
}Reading a file, parsing JSON, and writing a result is just async/await on top of fs/promises.
Notice the 'utf-8' argument on both calls. Without it, fs.readFile gives you a Buffer, which is a raw byte array. We pass utf-8 because we know the file is text. Always be explicit about encoding when you are working with text files.
JSON.parse can throw if the file is not valid JSON at all. That is a different failure from validation: it means the file is corrupted or someone gave you the wrong file. The classic backend pattern is to catch parse errors and return a clean error message instead of crashing.
One more async habit worth building now. Sequential awaits run one operation at a time, which is right when each step depends on the previous one. But if you have independent operations, like writing several files that do not touch each other, fire them together and wait once: await Promise.all([w1(), w2(), w3()]). All of them run concurrently, and the await resolves when every one has finished. Forgetting the await on Promise.all is a classic bug: your code keeps going while the writes are still in flight.
Quiz: Quiz
Loading practice…
Validation checklist: Read the messy book file yourself
Loading practice…