How to add data to the end of a file in Node.js?

Published December 25, 2020

To add to the end or append data to a file in Node.js, you can use the appendFile() asynchronous function from the fs (filesystem) module.

/*🔥 Append data to a file 🔥 */
fs.appendFile("file.txt", "Hello World!", "utf-8");

For example, Consider a file called logs.txt in which we have some log data and we want to add additional data to the end of the file.

// name of file
const file = "logs.txt";

// logs
const logData = "Request status: 200 OK";

Now let's use the appendFile() asynchronous function and pass:

  • the path of the file to append data as the first argument
  • the data as the second argument
  • the encoding as the third argument
  • and a callback function to execute after the data is successfully added to the file.

It can be done like this,

// require fs module
const fs = require("fs");

// name of file
const file = "logs.txt";

// logs
const logData = "\nRequest status: 200 OK";

// add logData to end of logs.txt file
// using fs.appendFile() asynchronous function
fs.appendFile(file, logData, "utf-8", () => {
  console.log("Log data added!");
});

And we have successfully added data to the end of the file! 🔥.

See this example live in repl.it.

Feel free to share if you found this useful 😃.

Share on: Facebook Twitter