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 :)

Share this