简体   繁体   中英

How to write each values from Object to each line in a text file

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');

}

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!');
 });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM