COLONELXO
COLONELXO

Reputation: 59

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

i'm trying to write a feed to a file using node.js. the problem is, it doesn't write all the 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?

Upvotes: 3

Views: 370

Answers (3)

Plaute
Plaute

Reputation: 4889

fs.writeFile comes with some options like flag. Default value of flag is w for write, so your data are replaced by the new one.

Use 'a' instead

{flag:'a'}

and you'll be fine.

But don't forget that WriteFile or AppendFile are upper layer in fs library which open and close file each time you need to add data.

Preferably, use fs.createWriteStream which returns a writable stream (writable file handle in other languages). Then use and reuse this stream when you need to write data in your file.

Upvotes: 0

ed.
ed.

Reputation: 2706

As @Robert says you should use appendFile, but also note that that change won't write out valid json. I'm not sure what output you're trying to achieve - it you just want the titles you could write out a txt file with a title on each line like so:

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 out 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);
      }
    });
  });

Upvotes: 0

Rob
Rob

Reputation: 11788

Just change fs.writeFile( to fs.appendFile( and you're fine.

fs.writeFile overwrites your file each time you call it whereas fs.appendFile adds to a file.

Upvotes: 3

Related Questions