Course outline · 0% complete

0/29 lessons0%

Course overview →

Persistence: Memory, Files, Databases

lesson 6-2 · ~11 min · 18/29

Where does the data live?

Every backend answers one question early: when the process stops, what survives?

  • In memory (a plain array or object): fastest, and gone the instant the server restarts. Fine for caches and prototypes.
  • A JSON file: survives restarts, using the fs skills from lesson 2-3 plus JSON.stringify. Breaks down when two requests write at once, and searching means reading everything.
  • A database: a separate program purpose-built for storing, searching, and safely updating data from many clients at once. Real apps live here.

The repository below is in-memory, and that is deliberate: the interface (create, find, remove) stays the same when you later swap the array for a database, so route handlers never know the difference. This boundary is called the persistence layer.

Memoryarray, objectfastestlost on restartJSON filefs + stringifysurvives restartsunsafe when sharedDatabaseSQL, indexesmany clients safelywhat real apps usedurability and safety grow left to right
Three homes for your data. Prototype in memory, then graduate to a database without changing your route handlers.

Code exercise · javascript

Run the seed of the repository. create stamps each row with an auto-incrementing id (the same job SQL's INTEGER PRIMARY KEY will do in the next lesson) and returns the stored row, so callers immediately know the new id.

Quiz

Two requests arrive at the same moment. Each reads users.json, adds one user to the array, and writes the whole file back. What can happen?

Code exercise · javascript

Your turn. Finish the repository: findById returns the matching row or null (use rows.find), and remove deletes by id, returning true if something was removed (use findIndex and splice).