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:
path of the fileto append data as the first argument
dataas the second argument
encodingas 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.