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

bookUpdating / Appending Files

Swipe to show menu

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.
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 23

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 1. Chapter 23
some-alt