Writing to a file only writes the last item, not all items, why?

I am trying to write a feed to a file using node.js. the problem is, it doesn't record all feeds, only the last 1.

var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
  console.log('title; ', article.title);
    fs.writeFile("articles.json", JSON.stringify(article.title), function(err) {
    if(err) {
          console.log(err);
    }
  });
});

      

Why?

+3


source to share


3 answers


Just change fs.writeFile(

to fs.appendFile(

and you're fine.



fs.writeFile

overwrites your file every time you call it while fs.appendFile

adding the file.

+3


source


As @Robert says you should use appendFile

, but also note that this change will not output the correct json. I'm not sure what result you are trying to achieve - you just need headers that you could write to a txt file with a header on each line:

var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
feedParser.parseUrl(url).on('article', function(article) {
  console.log('title; ', article.title);
    fs.appendFile("articles.txt", article.title + "\n", function(err) {
    if(err) {
          console.log(err);
    }
  });
});

      



To write json you can do:

var fs = require('fs');
var feedParser = require('ortoo-feedparser')
var url = "http://iwnsvg.com/feed";
let titles = [];

feedParser.parseUrl(url)
  .on('article', function (article) {
    console.log('title; ', article.title);
    titles.push(article.title);
  })
  .on('end', function () {
    fs.writeFile('articles.json', JSON.stringify({ titles }), function (err) {
      if (err) {
        console.log(err);
      }
    });
  });

      

0


source


fs.writeFile comes with some options like a flag . The default value for the w flag is writeable , so your data is overwritten with the new one.

Use 'a' instead

{flag:'a'}

      

and everything will be all right.

But don't forget that WriteFile or AppendFile are the top level in the fs library that open and close the file every time you need to add data.

Preferably use fs.createWriteStream which returns a writeable stream ( writeable file descriptor in other languages). Then use and reuse this stream whenever you need to write data to your file.

0


source







All Articles