---
title: "Download Images With node.js"
description: "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."
url: "https://h3manth.com/scribe/download-images-nodejs/"
canonical_url: "https://h3manth.com/scribe/download-images-nodejs/"
markdown_url: "https://h3manth.com/scribe/blog/download-images-nodejs.md"
publishDate: "2012-05-11T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["nodejs","bash","web"]
word_count: 134
reading_time_minutes: 1
x_markdown_tokens: 424
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# 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.

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