fs.writeFileSync()
replaces the entire contents of the file with your new content. It does not append content to the end. There are multiple ways to append to the end of a file.
The simplest mechanism is fs.appendFileSync()
and that will work for you, but it isn't very efficient to call that in a loop because internally, fs.appendfileSync()
will call fs.openSync()
, fs.writeSync()
and the fs.closeSync()
for each time through the loop.
It would be better to open the file once, do all your writing and then close the file.
const fs = require('fs');
const fd = fs.openSync('temp.txt', 'w');
for (let a = 0; a < 4; a++) {
fs.writeSync(fd, 'test' + a + '\n', 'utf-8');
}
fs.closeSync(fd);
Or, you can collect your data and then write it all at once:
let data = [];
for (let a = 0; a < 4; a++) {
data.push('test' + a + '\n');
}
fs.writeFileSync('temp.txt', data.join(''), 'utf-8');