0

I have an

object = { line1: 123, line2: 456 };

and I'd like to write it into a text file.

The output would be like this when the text file is opened.

123
456

I have tried this but it won't work

var json_data = require(`${__dirname}/output.json`);

var objectlength = Object.keys(json_data).length;
for ( var i = 0; i < objectlength; i++ ){
    console.log ( i );

    var write_to_txt = fs.writeFileSync(`${__dirname}/output.txt`, 
        json_data.line+i, null, '\t');

}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Tramyer
  • 13
  • 1
  • 8
  • One thing to remember is to read up on what the functions that you use, do, so you know what quirks to expect. Especially in this case, where [fs.writeFile](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) has a pretty hard to miss bit that says "When file is a filename, asynchronously writes data to the file, _replacing the file if it already exists_ (emphasis mine). data can be a string or a buffer." So successive calls to the same filename will wipe out whatever you wrote before. – Mike 'Pomax' Kamermans Aug 10 '19 at 04:51

1 Answers1

2

One method will be to use streams for this:

var stream = fs.createWriteStream(`${__dirname}/output.txt`, {flags:'a'});
Object.keys(json_data).map( function (item,index) {
    stream.write(json_data[key]+ "\n");
});
stream.end();

Consider going through here why you should prefer streams when continuously writing to same file. https://stackoverflow.com/a/43370201/6517383

Or you can use fs.appendFileSync instead like this:

Object.keys(json_data).map(key => {
 fs.appendFileSync(`${__dirname}/output.txt`, json_data[key]+ "\n", function (err) {
  if (err) throw err;
  console.log('Saved!');
 });
});
Black Mamba
  • 13,632
  • 6
  • 82
  • 105
  • 1
    @Tramyer the fix should be fairly obvious from looking at the second approach... change `json_data[key]` to `json_data[key]+ "\n"`. – Patrick Roberts Aug 10 '19 at 05:12