To append data to a file in Node.js, you can use the fs
(file system) module and the fs.appendFile()
function.
The fs.appendFile()
function takes a file path and a string or Buffer as arguments, and asynchronously writes the data to the end of the file. If the file does not exist, it will be created.
Here’s an example of how to use the fs.appendFile()
function to append a string to a file:
const fs = require('fs');
fs.appendFile('./file.txt', 'This is the new data to append', (err) => {
if (err) {
console.error(`Error appending to file: ${err}`);
} else {
console.log('Data appended to file successfully');
}
});
In this example, we use the fs.appendFile()
function to append the string 'This is the new data to append'
to the file.txt
file. If the operation is successful, the callback function will be called with a null
error object; otherwise, it will be called with an error object that describes the error that occurred.
Alternatively, you can use the fs.appendFileSync()
function to append data to a file synchronously. This function works in a similar way to fs.appendFile()
, but it blocks execution until the operation is complete.
const fs = require('fs');
try {
fs.appendFileSync('./file.txt', 'This is the new data to append');
console.log('Data appended to file successfully');
} catch (err) {
console.error(`Error appending to file: ${err}`);
}