Skip to content

Instantly share code, notes, and snippets.

@Torthu
Created November 6, 2013 15:48
Show Gist options
  • Save Torthu/7338405 to your computer and use it in GitHub Desktop.
Save Torthu/7338405 to your computer and use it in GitHub Desktop.
Download and save an array of images from a JSON file.
var http = require('http'),
fileJSON = require('./images.json'),
fs = require('node-fs'),
options,
assets = fileJSON.imageArr;
options = {
host: 'url.com',
port: 80,
path: 'path/to/images'
};
// download and save file
function getAndWrite(imageUrl) {
var request = http.get({ host: options.host, port: options.port, path: options.path + imageUrl }, function(res) {
var imagedata = ''; // image returns in chunks
res.setEncoding('binary');
// assemple image chunks
res.on('data', function(chunk){
imagedata += chunk;
});
// create directory and write file (node-fs, not fs)
res.on('end', function(){
dir = imageUrl.split('/');
dir.pop();
dir = dir.join('/');
// make dir
fs.mkdir('./image/' + dir, 0777, true, function (err) {
if (err) {
console.log(err);
} else {
// write file
fs.writeFile('image' + imageUrl, imagedata, 'binary', function(err){
if (err) throw err;
});
}
});
});
});
}
// Loop through images to download
for(var i = 0;i<assets.length;i++) {
getAndWrite(assets[i]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment