node append to file code example
Example 1: How to append to a file in Node?
const fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('Saved!');
});
const fs = require('fs');
fs.appendFileSync('message.txt', 'data to append');
Example 2: Append text into a file nodejs
const fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('Saved!');
});
If message.txt doesnt exist, It will gonna create that too
Example 3: Append text into a file nodejs
Synchronously
const fs = require('fs');
fs.appendFileSync('message.txt', 'data to append');
Example 4: fs.writefile
const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
fs.writeFileSync('/tmp/test-sync', 'Hey there!');
Example 5: node js write file
const fs = require('fs');
let path = 'ghetto_gospel.txt';
let buffer = new Buffer('Those who wish to follow me\nI welcome with my hands\nAnd the red sun sinks at last');
fs.open(path, 'w', function(err, fd) {
if (err) {
throw 'could not open file: ' + err;
}
fs.write(fd, buffer, 0, buffer.length, null, function(err) {
if (err) throw 'error writing file: ' + err;
fs.close(fd, function() {
console.log('wrote the file successfully');
});
});
});