This blog describes how to append in a text file in Node.js.
To append to a text file in Node.js, you can use the fs.appendFile()
function from the built-in fs
(File System) module. This function appends data to a file, creating the file if it does not exist. Here’s how you can use it.
const fs = require('fs');
// Path to the file
const filePath = 'source.txt';
// Data to append
const dataToAppend = 'New data to append to the file.\n';
// Append data to the file
fs.appendFile(filePath, dataToAppend, (err) => {
if (err) {
console.error('Error appending to file:', err);
return;
}
console.log('Data appended to file successfully.');
});
The fs.appendFile()
function takes three arguments.
- The path to the file.
- The data to append.
- A callback function that gets called after the operation completes. It receives an error object if an error occurred during the operation.
This code will append the specified data to the end of the file. If the file does not exist, it will be created.
source.txt
Output
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go
20+ Interview Questions on Go Programming Language