Node.JS Twitter Client Example

Posted by Tully on Fri 01 March 2013

Lately I have been working a lot with Node.JS. Today I wanted to build a simple twitter command line search.

To get the code below working, you will need to have the colors module.

You can get the colors module by either adding it to your packages.json file and running the command npm install or running npm install colors to install globally.

var http = require('http');
var colors = require('colors');

var getTweets = function(query, cb) {
    var data = "";
    var options = {
        host: 'search.twitter.com',
        port: 80,
        path: '/search.json?q=' + query,
        method: 'GET'
    }

    var request = http.request(options, function(response) {
        response.on('data', function(chunk) {
            data += chunk.toString();
        });

        response.on('end' , function() {
            if (JSON.parse(data) && data.length) {
                data = JSON.parse(data);
            }
            cb(data);
        });
    });
    request.end();
}

if (!process.argv[2]) {
    console.log('Usage: node ' + process.argv[1] + ' search_query');
    process.exit(0);
}

var searchQuery = encodeURIComponent(process.argv.splice(2).join(' '));

var tweets = getTweets(searchQuery, function(data) {
    if (data.results.length) {
        console.log('Search Completed in: ' + data.completed_in + ' seconds.');
    } else {
        console.log('No Results found for "' + decodeURIComponent(searchQuery) + '"');
        process.exit(0);
    }

    var tweet, out;
    for (i in data.results) {
        var tweet = data.results[i];
        out = "[" + tweet.created_at + "]\n";
        out += tweet.text.green;
        console.log(out + "\n");
    }
});