Created
April 14, 2016 01:51
-
-
Save malbernaz/b29104264bf5ec2f89b618cd063c6152 to your computer and use it in GitHub Desktop.
Download a bunch of cat pics (thanks to the Cat API)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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