Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show last 20 tweets with twitter api on express.js with node.js?

I want use Twitter API (https://www.npmjs.com/package/twitter) and here are the thinks I'd like to add:

app.js & package.json

var express = require("express"),
path        = require("path"),
http        = require("http"),
twitter     = require("twitter"),
app         = express();

http.createServer(app).listen(3000);

twitter_data.js

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

var params = {screen_name: 'nodejs'};

client.get('statuses/user_timeline', params, function(error, tweets, response){
  if (!error) {
    console.log(tweets);
  }
});
like image 464
kkarthik s Avatar asked Sep 08 '15 06:09

kkarthik s


1 Answers

I'll try to keep it short, here we go:

Install express-generator module first: npm install -g express-generator

Run express --hbs (you can choose Jade or anything else, but I prefer Handlebars, so I'll continue with that)

Go to the folder and install dependencies: npm install

Install twitter module: npm install --save twitter

Go to Twitter's Application Management Page and create your app. Get the necessary keys: consumer_key, consumer_secret, access_token_key, and access_token_secret.

After this point, I'd like to share the actual codes instead of explaining what to do

Here's /routes/index.js file:

var express = require('express');
var Twitter = require('twitter');

var router = express.Router(); 
var client = new Twitter({
  consumer_key: 'XXX',
  consumer_secret: 'XXX',
  access_token_key: 'XXX',
  access_token_secret: 'XXX'
});

router.get('/', function(req, res, next) {
  // https://dev.twitter.com/rest/reference/get/statuses/user_timeline
  client.get('statuses/user_timeline', { screen_name: 'nodejs', count: 20 }, function(error, tweets, response) {
    if (!error) {
      res.status(200).render('index', { title: 'Express', tweets: tweets });
    }
    else {
      res.status(500).json({ error: error });
    }
  });
});

module.exports = router;

And here's /views/index.hbs file:

<ul>
  {{#each tweets }}
  <li>{{ this.text }}</li>
  {{/each }}
</ul>

When you save them all and run npm start, you can see the results at http://localhost:3000

like image 197
Gökay Gürcan Avatar answered Oct 04 '22 20:10

Gökay Gürcan