I am trying to append a string to a log file. However writeFile will erase the content each time before writing the string.
JavaScript
x
5
1
fs.writeFile('log.txt', 'Hello Node', function (err) {
2
if (err) throw err;
3
console.log('It's saved!');
4
}); // => message.txt erased, contains only 'Hello Node'
5
Any idea how to do this the easy way?
Advertisement
Answer
For occasional appends, you can use appendFile
, which creates a new file handle each time it’s called:
JavaScript
1
7
1
const fs = require('fs');
2
3
fs.appendFile('message.txt', 'data to append', function (err) {
4
if (err) throw err;
5
console.log('Saved!');
6
});
7
JavaScript
1
4
1
const fs = require('fs');
2
3
fs.appendFileSync('message.txt', 'data to append');
4
But if you append repeatedly to the same file, it’s much better to reuse the file handle.