CURL and Twitter search
In this post we will be talking about getting data from other websites, something cURL have been doing for eons, but in server-side JS speak it is called HTTP Client and here you will learn how to use it.
The basic syntax is this:
req = new HTTP.ClientRequest(url); res = req.send(true);
As you can see all you need is to pass an URL to the HTTP.ClientRequest instantiation and then call the 'send' method to start the request and get the response, from where you get the data.
So why not to build a basic (yet pretty) Twitter search tool to demonstrate its simplicity?
I love simplicity so here we go:
var txt,url,req,res,twits,view,data={};
txt = request.post.q || 'Home';
url = 'http://search.twitter.com/search.json?lang=en&q='+txt;
req = new HTTP.ClientRequest(url);
res = req.send(true);
twits = JSON.parse(res.data);
data.query = txt;
data.title = txt || 'Home';
data.twits = twits.results;
view = new Template().process('twit',data);
response.write(view);
Ooh beauty, I know you when I see you!
Not much to explain here, just send a request to Twitter for the latest twits about a specific query and as soon as we get the data we parse it and render it using our template du jour:
<html>
<head>
<title>Twit Search</title>
<link rel="stylesheet" type="text/css" href="twit.css">
</head>
<body>
<h1><img src="twitlogo.png" /></h1>
<div id="hose">
<form id="search" method="post">
<input type="textbox" id="q" name="q" value="search" placeholder="search" onfocus="this.value=''"/>
</form>
<h2>$(data.title)</h2>
$code( for(i in data.twits){ )
<li>
<img src="$(data.twits[i].profile_image_url)">
<h3><a href="http://twitter.com/$(data.twits[i].from_user)">$(data.twits[i].from_user)</a></h3>
<p>$(data.twits[i].text.replace(new RegExp(data.query,'gi'),'<b>'+data.query+'</b>'))</p>
<small>$(new Date(data.twits[i].created_at).format('D, d M Y H:i:s'))</small>
</li>
$code( } )
</div>
</body>
</html>
Go grab the whole enchilada from Github at TwitJS
