Append data to a File using Node FS

Node.js Append to a File

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.

Node.js Append File

In this Node.js Tutorial, we shall learn

Syntax of appendFile()

fs.appendFile(filepath, data, options, callback_function);

Callback function is mandatory and is called when appending data to file is completed.

Syntax of appendFileSync()

fs.appendFileSync(filepath, data, options);

where :

  • filepath [mandatory] is a String that specifies file path
  • data [mandatory] is what you append to the file
  • options [optional] to specify encoding/mode/flag

Note : If file specified does not exist, a new file is created with the name provided, and data is appended to the file.

 

Example : Node.js Append data to file asynchronously using appendFile()

To append data to a file asynchronously in Node.js, use appendFile() function of Node FS as shown below :

File before appending

File after appending

 

Example : Node.js Append data to file synchronously using appendFileSyc()

To append data to a file synchronously in Node.js, use appendFileSync() function of Node FS as shown below :

File before appending

File after appending

 

Conclusion :

In this tutorial – Node.js Append to a File, we have learnt to append data to a file in Node.js, synchronously and asynchronously using appendFileSync() and appendFile() functions of Node FS respectively with Example Node.js programs.