-2

Past research I've done on this topic says that this code:

    const filestream = require('fs');
    for(let a = 0; a < 4; a++) {
        fs.writeFileSync('test.txt', 'test' + a + '\n', 'UTF-8', {'flags': 'a'});
    }

should output

test0
test1
test2
test3

to test.txt. However, all I'm seeing is test3, indicating that each write to the file is overwriting all existing text. Despite my use of the 'a' flag. What's going on here?

John Smith
  • 107
  • 1
  • 13
  • 2
    Does this answer your question? [How to append to a file in Node?](https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node) – JBis Dec 04 '19 at 03:14

2 Answers2

0

I think there is another function you're supposed to use for this instead, would you be able to try the following?

fs.appendFileSync('test.txt', 'test' + a + '\n');
tkingston
  • 114
  • 6
  • https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node/43370201#43370201 AppendFile isn't good to use for large scale file appending. – John Smith Dec 04 '19 at 03:17
-1

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');
jfriend00
  • 683,504
  • 96
  • 985
  • 979