0

I'm trying to use Twitter API to get all tweets in NYC. Now I want to store all these tweets to my local json file(data.json). But after running this code, I found only the last tweet get stored not all of them.

var Twitter = require('twitter');
const fs = require('fs');

var client = new Twitter({
  consumer_key: 'XXXXXXXXXXXX',
  consumer_secret: 'XXXXXXXXXXXX',
  access_token_key: 'XXXXXXXXXXXX',
  access_token_secret: 'XXXXXXXXXXXX'
});

client.stream('statuses/filter', {locations: '-74,40,-73,41'}, function(stream) {
  stream.on('data', function(tweet) {
    fs.writeFile('./data.json', JSON.stringify(tweet), 'utf-8');
    console.log(tweet.text);  
  });

  stream.on('error', function(error) {
    throw error;
  });
});

How to store all of them in data.json? It's kind of like what '+=' operation does but I'm new to js...

Wei Shi
  • 1
  • 1

1 Answers1

0

It sounds like you need to open your file first, parse the JSON, append your new result to the array, transform it back into a string and save it again.

I believe this is what you are looking for here: https://stackoverflow.com/a/36093141/5884189

Community
  • 1
  • 1
mmryspace
  • 689
  • 1
  • 9
  • 18