Skip to content

Instantly share code, notes, and snippets.

@tanepiper
Created November 24, 2010 00:16
Show Gist options
  • Save tanepiper/712830 to your computer and use it in GitHub Desktop.
Save tanepiper/712830 to your computer and use it in GitHub Desktop.
var http = require('http');
var fs = require('fs');
var url = require('url');
var word = process.argv[2];
var google = http.createClient(80, 'ajax.googleapis.com');
var request = google.request('GET', '/ajax/services/search/images?q=' + word + '&v=1.0&safe=off', {'host': 'ajax.googleapis.com'});
request.end();
request.on('response', function (response) {
var data = '';
response.setEncoding('utf8');
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function() {
if (response.statusCode != '200') {
throw new Error('Error');
} else {
var result = JSON.parse(data);
var first = result.responseData.results[0].url;
var firstUrl = url.parse(first);
var filename = firstUrl.pathname.split('/').pop();
var image = http.createClient(80, firstUrl.hostname);
var request2 = image.request('GET', firstUrl.pathname, {'host': firstUrl.hostname});
request2.end();
var out = fs.createWriteStream(filename);
request2.on('response', function(response2) {
response2.on('data', function (chunk) {
out.write(chunk);
});
response2.on('end', function() {
console.log('File ' + filename + ' saved');
})
})
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment