15

How can I append to a file using fs.write()?

Using fs.write on the same files overwrites the content:

var fs = require('fs');
try {
    fs.write("file.txt", "Hello World", 'w');
    fs.write("file.txt", "Hello World", 'w');
} catch(e) {
    console.log(e);
}
ThorSummoner
  • 16,657
  • 15
  • 135
  • 147

1 Answers1

33

Use append mode a instead of [over]write mode w in the fs.write call.

var fs = require('fs');
try {
    fs.write("file.txt", "Hello World", 'a');
    fs.write("file.txt", "Hello World", 'a');
} catch(e) {
    console.log(e);
}

I inferred this based on the python open() C fopen documentation; Glad it worked, other file modes may work but were not tested by me.

ThorSummoner
  • 16,657
  • 15
  • 135
  • 147
  • Can we out data extracted from 2 functions into 2 seperate columns in csv ? – Srinivas08 Dec 14 '16 at 13:09
  • @Srinivas08 Its possible sure, if you can get each row's next column in order, [I would suggest doing so with two generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators), and append the values one at a time in the right order, each column for each row, it might work. However that might be a lot of overhead for a large amount of data to do that manny writes, and it would be really easy to make a malformed csv this way. If possible I'd suggest abstract your data into a two dimensional hash/dictionary and using a csv exporter. – ThorSummoner Dec 15 '16 at 00:08