Skip to content
This repository
Newer
Older
100644 41 lines (38 sloc) 1.516 kb
1696cc7f » bjouhier
2013-06-22 added tutorial to v0.4 branch
1 "use strict";
14a0189a » bjouhier
2014-01-16 fixed tutorial
2 var ez = require('ez-streams');
1696cc7f » bjouhier
2013-06-22 added tutorial to v0.4 branch
3 var url = require('url');
4 var qs = require('querystring');
5
6 var begPage = '<html><head><title>My Search</title></head></body>' + //
7 '<form action="/">Search: ' + //
8 '<input name="q" value="{q}"/>' + //
9 '<input type="submit"/>' + //
10 '</form><hr/>';
11 var endPage = '<hr/>generated in {ms}ms</body></html>';
12
14a0189a » bjouhier
2014-01-16 fixed tutorial
13 ez.devices.http.server(function(request, response, _) {
1696cc7f » bjouhier
2013-06-22 added tutorial to v0.4 branch
14 var query = qs.parse(url.parse(request.url).query),
15 t0 = new Date();
16 response.writeHead(200, {
17 'Content-Type': 'text/html; charset=utf8'
18 });
19 response.write(_, begPage.replace('{q}', query.q || ''));
20 response.write(_, search(_, query.q));
21 response.write(_, endPage.replace('{ms}', new Date() - t0));
22 response.end();
23 }).listen(_, 1337);
24 console.log('Server running at http://127.0.0.1:1337/');
25
26 function search(_, q) {
27 if (!q || /^\s*$/.test(q)) return "Please enter a text to search";
28 // pass it to Google
14a0189a » bjouhier
2014-01-16 fixed tutorial
29 var json = ez.devices.http.client({
1696cc7f » bjouhier
2013-06-22 added tutorial to v0.4 branch
30 url: 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' + q,
31 proxy: process.env.http_proxy
32 }).end().response(_).checkStatus(200).readAll(_);
33 // parse JSON response
34 var parsed = JSON.parse(json);
35 // Google may refuse our request. Return the message then.
36 if (!parsed.responseData) return "GOOGLE ERROR: " + parsed.responseDetails;
37 // format result in HTML
38 return '<ul>' + parsed.responseData.results.map(function(entry) {
39 return '<li><a href="' + entry.url + '">' + entry.titleNoFormatting + '</a></li>';
40 }).join('') + '</ul>';
41 }
Something went wrong with that request. Please try again.