← Back to Node.js Course | Chapter 5: File System | Lesson 3 of 7

Appending

appendFile adds text to the end of a file without erasing what is there.

In this page:

  1. Appending
Syntax
javascript
fs.appendFileSync('path', data);
fs.appendFile('path', data, (err) => {
  // handle err
});

Appending

appendFile and appendFileSync create the file if needed and add data at the end, which suits logs. Each call opens and closes the file, so for heavy logging keep a write stream open with the a flag.

Note: Add a newline yourself; append does not.

Example: Appending

javascript
const fs = require("fs");
fs.writeFileSync("log.txt", "");
for (const msg of ["start", "work", "end"]) fs.appendFileSync("log.txt", msg + "\n");
console.log(fs.readFileSync("log.txt", "utf8").trim().split("\n"));

// Output:
// [ 'start', 'work', 'end' ]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the newline between entries
  2. Appending in tight loops with open and close each time
  3. Expecting append to insert at the start
Chapter Summary
  • appendFile adds to the end
  • It creates missing files
  • You supply the newline
  • Streams suit heavy logging
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.