Skip to content

Instantly share code, notes, and snippets.

@malbernaz
Created April 14, 2016 01:51
Show Gist options
  • Save malbernaz/b29104264bf5ec2f89b618cd063c6152 to your computer and use it in GitHub Desktop.
Save malbernaz/b29104264bf5ec2f89b618cd063c6152 to your computer and use it in GitHub Desktop.
Download a bunch of cat pics (thanks to the Cat API)
'use strict'
const http = require('http'),
fs = require('fs')
let i = 0,
url = 'http://thecatapi.com/api/images/get?format=src&type=jpg'
function request(url) {
let dest = './img/' + i + '.jpg',
file = fs.createWriteStream(dest)
if (i < 80) {
http.get(url, (res) => {
console.log(`Got code: ${res.statusCode}`)
console.log(res.headers['content-type'])
console.log(`i: ${i}`)
if (res.statusCode == 302)
request(res.headers.location)
if (res.statusCode == 200) {
res.pipe(file)
i++
url = 'http://thecatapi.com/api/images/get?format=src&type=jpg'
request(url)
}
if (res.statusCode == 403) {
res.pipe(file)
url = 'http://thecatapi.com/api/images/get?format=src&type=jpg'
request(url)
}
}).on('error', (e) => {
console.log(`Got error: ${e.message}`)
})
}
}
request(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment