简体   繁体   中英

node twitter npm package

I've installed node-twitter via npm and have created an index.js file with the code below. When I run node index.js in the console I'm not getting any response. I've included my own keys and secrets so that doesn't appear to be the issue.

var Twitter = require('twitter');

var client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});

client.stream('statuses/filter', {track: 'nyc'},  function(stream){
  stream.on('data', function(tweet) {
    console.log(tweet.text);
  });

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

You're connecting to one of Twitter's streaming endpoints, so you will only see updates if someone posts a tweet with the text 'nyc' in it at that precise moment.

I suspect this is not your intention, and you instead wish to search for the most recent tweets containing the text 'nyc', as below:

client.get('/search/tweets.json?q=nyc', function(error, tweets, response){
  if(error) throw error;
  console.log(tweets);
});

The Twitter search API documentation is here . If you actually do wish to stream tweets, I recommend using something like forever.js to keep your script running long enough to listen for tweets and output them.

Edit: Since you would like to stream the tweets as they come in, you can use forever.js to keep your script running, as below:

var forever = require('forever-monitor');

var child = new (forever.Monitor)('twitter.js', {
    max: 1,
    silent: false,
    args: []
});

child.on('exit', function () {
    console.log('twitter.js has exited after 3 restarts');
});

child.start();

Where twitter.js is the file posted in the question. If you want to search backwards or forwards from a specified time, you can find details on how to do so in the Twitter API docs .

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