Skip to content

Instantly share code, notes, and snippets.

@olimart
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olimart/d6bb4491746c5684dfd8 to your computer and use it in GitHub Desktop.
Save olimart/d6bb4491746c5684dfd8 to your computer and use it in GitHub Desktop.
Node search
//helper method for writing out json payloads
var json = function(res, data) {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
if(typeof data === "string") res.write(data);
else res.write(JSON.stringify(data));
res.end();
};
/*
* Routes
*/
// Index Page
app.get('/', function(request, response, next) {
response.render('index');
});
// Search
app.get('/search', function (req, res, next) {
var query = req.param('query');
var lang = req.param('lang') || 'en';
var tld = req.param('tld') || 'com';
if (typeof query !== 'undefined') {
Google(query, lang, tld, function(err, data) {
json(res, data);
// TODO expect JSON Array
});
} else {
// should raise error if missing query params
res.writeHead(400);
var response = {
status : 400,
success : 'Query missing'
}
res.end(JSON.stringify(response));
}
});
/**
* Expose a `Google` client.
*/
module.exports = Google;
function Google(query, options){
google.resultsPerPage = 10;
var nextCounter = 0;
google(query, function(err, next, links){
if (err) console.error(err);
results = [];
for (var i = 0; i < links.length; ++i) {
results.push(
{"title": links[i].title + ","
"link": links[i].link) + ","
"description": links[i].description
});
//console.log(links[i].title + ' - ' + links[i].link); //link.href is an alias for link.link
//console.log(links[i].description + "\n");
}
if (nextCounter < 1) {
nextCounter += 1;
if (next) next();
}
return results
// TODO results should return an array
});
}
@alexbeletsky
Copy link

I see the problem in you Google function, https://gist.github.com/olimart/d6bb4491746c5684dfd8#file-search-js-L53.

It's signature, Google(query, options), but you are calling it, Google(query, lang, tld, function(err, data) which is wrong. Google function is wrong as well.

Here is the working version, based on express.js and google.

https://gist.github.com/alexbeletsky/a3ce02a05790e24a3176

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment