How to append files in Node.js
Appending data to existing files is essential for logging, data collection, and incremental file operations in Node.js applications.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented file appending in numerous backend services over 25 years of development.
From my expertise, the most straightforward approach is using the fs.appendFile() method, which adds content to the end of files without overwriting existing data.
This is particularly useful for log files and data accumulation scenarios.
Use fs.appendFile() to add content to the end of an existing file.
const fs = require('fs')
fs.appendFile('log.txt', 'New log entry\n', (err) => {
  if (err) throw err
  console.log('Data appended successfully')
})
Here fs.appendFile() takes the filename, data to append, and a callback function. The method adds the new content to the end of the file, creating the file if it doesn’t exist. The newline character \n ensures each append creates a new line, which is essential for readable log files and structured data.
Best Practice Note:
This is the same file appending approach we use in CoreUI backend services for activity logging and error tracking.
For high-frequency appends, consider using fs.createWriteStream() with the append flag for better performance and automatic buffering.



