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

Published December 26, 2020

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

/*🔥 Append data to a file 🔥 */
fs.appendFileSync("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 appendFileSync() synchronous 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

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.appendFileSync() synchronous function
fs.appendFileSync(file, logData, "utf-8");

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