Using Files as Simple Storage
Swipe to show menu
So far, you have learned how to:
- Read data from a file;
- Write data to a file;
- Append new content.
Now it's time to use files as a simple storage system.
Why We Need Structured Data
Storing plain text is not enough for real applications.
For example:
First note
Second note
This is hard to manage because:
- We can't easily update a specific note;
- We can't organize data;
- We can't add extra information.
Using JSON for Storage
To store structured data, we use JSON.
JSON looks like a JavaScript object:
[
{ "text": "First note" },
{ "text": "Second note" }
]
This format allows us to:
- Store multiple items;
- Organize data clearly;
- Work with it in code.
Step 1: Read Data from a File
const fs = require('fs');
const data = fs.readFileSync('notes.json', 'utf-8');
This returns a string.
Step 2: Convert JSON to JavaScript
const notes = JSON.parse(data);
Now notes is a real array we can work with.
Step 3: Update Data
notes.push({ text: 'New note' });
We add a new note to the array.
Step 4: Save Data Back to the File
fs.writeFileSync('notes.json', JSON.stringify(notes));
JSON.stringifyconverts JavaScript back to JSON;- the file is updated with new data.
Full Example
const fs = require('fs');
// Read file
const data = fs.readFileSync('notes.json', 'utf-8');
// Convert to JS
const notes = JSON.parse(data);
// Update data
notes.push({ text: 'Learn Node.js' });
// Save back
fs.writeFileSync('notes.json', JSON.stringify(notes));
Handling First Run (Empty File)
If the file does not exist or is empty, the app will crash.
We can fix this by starting with an empty array:
let notes = [];
try {
const data = fs.readFileSync('notes.json', 'utf-8');
notes = JSON.parse(data);
} catch (error) {
notes = [];
}
Everything was clear?
Thanks for your feedback!
Section 1. Chapter 24
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Section 1. Chapter 24