File Persistence with JSON
Introduction: Moving Beyond In-Memory Storage
Welcome back! In the last lesson, you learned how to use the Repository Pattern to keep your data logic separate from your business logic. Up until now, you have been storing your data in memory, which means all your tasks disappear every time you restart your app. This is fine for learning, but in real-world applications, you need your data to persist even after the server restarts.
In this lesson, you will learn how to save your data to a file using JSON. This is called file-based persistence. By the end of this lesson, you will know how to read and write your tasks to a JSON file, making your app more like a real backend service.
Recap: Task Data and Project Structure
Let’s quickly remind ourselves of the Task data structure and where our data lives. You have a Task type that looks like this:
Previously, you stored tasks in memory using an array. Now, you will use a file called data/tasks.json to store your tasks. This file will look like this when empty:
This file will grow as you add, update, or delete tasks. The rest of your project structure stays the same, but now your data will be saved in a file instead of just in memory.
Reading and Writing JSON Files in Node.js
To work with files in Node.js, you use the built-in fs/promises module. This module lets you read and write files using promises, which means you can use async and await for cleaner code.
Here’s a simple example of reading and writing a JSON file:
Explanation:
fs.readFilereads the file as a string.JSON.parseturns the string into a JavaScript array.fs.writeFilesaves the array back to the file as a JSON string.JSON.stringify(tasks, null, 2)makes the JSON file easy to read by adding indentation. The second and third arguments inJSON.stringify(tasks, null, 2)ensure the JSON file is pretty-printed with 2-space indentation, making it easier to inspect manually.
Output Example:
If you call writeTasks([{ id: 1, title: "Learn Next.js", completed: false }]), your tasks.json file will look like:
