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 :)
#javascript#linux
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.