Member-only story
How to Append Data to a File using Node FS
2 min readSep 2, 2022
To append data to file in Node.js, use Node FS appendFile() function for asynchronous file operation or Node FS appendFileSync() function for synchronous file operation.
Example 1 — Node.js Append data to file asynchronously using appendFile()
var fs = require('fs');var data = "\nAdd this line to the file.";
// append data to filefs.appendFile('sample.txt',data, 'utf8',// callback functionfunction(err) {if (err) throw err;// if no errorconsole.log("Data is appended to file successfully!")});
Output of the file sample.txt:
Add this line to the file.
Example 2 — Node.js Append data to file synchronously using appendFileSyc()
var fs = require('fs');var data = "\n\nAdd this line to the file.";// append data to filefs.appendFileSync('sample.txt',data, 'utf8');console.log("Data is appended to file successfully.")