Appending
appendFile adds text to the end of a file without erasing what is there.
In this page:
Syntax
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
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
- Forgetting the newline between entries
- Appending in tight loops with open and close each time
- 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: