arun
arun

Reputation: 21

Nodejs - How to zip multiple images

I have an array of image url's and I want to be able to retrieve all the images and zip them up. How do I go about this?

Upvotes: 2

Views: 2271

Answers (1)

nesdev
nesdev

Reputation: 416

To download all images, you can use request module:

var fs = require('fs'),
    request = require('request');

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};
//Now, you can simply use `download(imageUrl,localFilename,function(){ /*return or print something here*/ });`
download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
  console.log('done');
});

To zip all files (in your case, images) in a folder, you should try archiver lib:

var file_system = require('fs');
var archiver = require('archiver');

var output = file_system.createWriteStream('target.zip');
var archive = archiver('zip');

output.on('close', function () {
    console.log(archive.pointer() + ' total bytes');
    console.log('archiver has been finalized and the output file descriptor has closed.');
});

archive.on('error', function(err){
    throw err;
});

archive.pipe(output);
archive.bulk([
    { expand: true, cwd: 'source', src: ['**'], dest: 'source'}
]);
archive.finalize();

or zipFolder lib:

var zipFolder = require('zip-folder');

zipFolder('/path/to/the/folder', '/path/to/target.zip', function(err) {
    if(err) {
        console.log('Oh no! Error!', err);
    } else {
        console.log('Nice! :)');
    }
});

Upvotes: 3

Related Questions