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

bookUpdating / Appending Files

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

To add new content instead of replacing it, you can use:

fs.appendFileSync()

This method adds data to the end of the file.

Example

const fs = require('fs');

fs.appendFileSync('notes.txt', '\nSecond note');
  • \n creates a new line;
  • The new note is added below the existing content.

Result in the File

First note
Second note

Each time you run this code, a new line will be added.

writeFileSync vs appendFileSync

It is important to understand the difference:

  • writeFileSync: replaces all content;
  • appendFileSync: adds new content.

Example Comparison

// Overwrites file
fs.writeFileSync('notes.txt', 'New content');

// Appends to file
fs.appendFileSync('notes.txt', '\nAnother note');

When to Use Appending

Appending is useful when you want to:

  • Store multiple records (like notes or logs);
  • Keep history of actions;
  • Add new data without losing old data.
すべて明確でしたか?

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

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

セクション 1.  23

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 1.  23
some-alt