Download images with node.js
All of a sudden /me gets silly and crazy thoughts to do useless tasks that just pleases me only!
Here is one such task, the code below downloads images from a given URI to the filesystem.
Prerequisites
- node.js
$bash < <(curl http://h3manth.com/njs)
- request and cheerio
npm install cheerio
npm install request
The script
function getImages(uri) { var request = require('request'); var url = require('url'); var cheerio = require('cheerio'); path = require('path') var fs = require('fs'); request(uri, function (error, response, body) { if (!error && response.statusCode == 200) { $ = cheerio.load(body) imgs = $('img').toArray() console.log("Downloading...") imgs.forEach(function (img) { //console.log(img.attribs.src) process.stdout.write("."); img_url = img.attribs.src if (/^https?:\/\//.test(img_url)) { img_name = path.basename(img_url) request(img_url).pipe(fs.createWriteStream(img_name)) } }) console.log("Done!") } }) } getImages("http://imgur.com/gallery")
Yes the same code can be extended to download different types of data/media :)
Recent blog posts
- watir-webdriver web inspector
- gem list to gemfile
- Packing ruby2.0 on debian.
- Made it into The Guinness Book!
- to_h in ruby 2.0
- Filter elements by pattern jQuery.
- Better HTML password fields for mobile ?
- Grayscale image when user offline
- nth-child CSS pseudo-class Christmas colors
- EventEmitter in nodejs