Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Using Files as Simple Storage | Section
/
Node.js Fundamentals

bookUsing Files as Simple Storage

メニューを表示するにはスワイプしてください

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.stringify converts 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 = [];
}
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  24

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  24
some-alt