Permalink
Browse files

realtime search example

  • Loading branch information...
1 parent 2d5eb8b commit 78380c1bef04854f893089740fe7307220cb0b51 @tj committed Jul 28, 2011
Showing with 94 additions and 0 deletions.
  1. +54 −0 examples/form.html
  2. +40 −0 examples/web-realtime.js
View
54 examples/form.html
@@ -0,0 +1,54 @@
+<html>
+ <head>
+ <title>Realtime Search</title>
+ <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
+ <style>
+ body {
+ padding: 50px;
+ font: 14px "helvetica neue", helvetica, arial, sans-serif;
+ }
+ .desc {
+ margin: 3px;
+ font-size: 12px;
+ color: #888;
+ }
+ input {
+ outline: none;
+ }
+ ul {
+ margin: 0;
+ padding: 0;
+ }
+ ul li {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ padding: 3px;
+ }
+ </style>
+
+ <script>
+ o = $; // because $ is lame
+
+ o(function(){
+ o('[name=query]').keyup(function(){
+ var val = o(this).val().trim()
+ , results = o('#results').empty();
+ if (!val) return;
+ o.get('/search?q=' + val, function(res){
+ res.forEach(function(res){
+ results.append('<li>' + res + '</li>');
+ });
+ });
+ });
+ });
+ </script>
+ </head>
+ <body>
+ <form>
+ <input type="text" placeholder="Search" name="query" autocomplete="off" />
+ <p class="desc">Try "express", "mongodb", "hacker" ...</p>
+ </form>
+ <ul id="results"></ul>
+ </body>
+</html>
View
40 examples/web-realtime.js
@@ -0,0 +1,40 @@
+
+/**
+ * Module dependencies.
+ */
+
+var http = require('http')
+ , reds = require('../')
+ , search = reds.createSearch('webpages')
+ , parse = require('url').parse
+ , qs = require('querystring')
+ , fs = require('fs');
+
+// urls, could be in redis or another db
+
+var urls = fs.readFileSync(__dirname + '/urls', 'utf8').split('\n');
+
+// First run:
+// $ node examples/web-index
+
+http.createServer(function(req, res){
+ var url = parse(req.url)
+ , query = qs.parse(url.query);
+
+ if ('/search' == url.pathname) {
+ search.query(query.q, function(err, ids){
+ // ids are simply indexes in this case
+ var json = JSON.stringify(ids.map(function(id){ return urls[id]; }));
+ res.setHeader('Content-Type', 'application/json');
+ res.setHeader('Content-Length', json.length);
+ res.end(json);
+ });
+ } else {
+ res.setHeader('Content-Type', 'text/html');
+ fs.readFile(__dirname + '/form.html', 'utf8', function(err, buf){
+ res.end(buf);
+ });
+ }
+}).listen(3000);
+
+console.log('App started on port 3000');

0 comments on commit 78380c1

Please sign in to comment.