-->

How to zip multiple folders generating multiple .z

2020-07-24 06:25发布

问题:

My folder structure looks like this:

- /projects
- /projects/proj1
- /projects/proj2
- /projects/proj3
- /zips

For each folder in projects (proj1, proj2 and proj3) I want to zip contents of each of those folders and generate proj1.zip, proj2.zip and proj3.zip in /zips folder.

Following example function generates single zip file from proj1 folder

zip = require('gulp-zip');
gulp.task('default', function () {
    return gulp.src('./projects/proj1/*')
        .pipe(zip('proj1.zip'))
        .pipe(gulp.dest('./zips'));
});

But how I can execute such task for each folder in projects? I can get all folders to zip by gulp.src('./projects/*') but what then?

回答1:

Old question I know and I am pretty new to gulp so this might be considered a hack but I have just been trying to do what you are after and I ended up with this.

My file structure is this:

proj
proj/dist
proj/dist/sub01
proj/dist/sub02
proj/dist/sub03
proj/zipped

And my task ended up like this:

var gulp = require("gulp");
var foreach = require("gulp-foreach");
var zip = require("gulp-zip");

gulp.task("zip-dist", function(){
   return gulp.src("./dist/*")
       .pipe(foreach(function(stream, file){
          var fileName = file.path.substr(file.path.lastIndexOf("/")+1);
          gulp.src("./dist/"+fileName+"/**/*")
              .pipe(zip(fileName+".zip"))
              .pipe(gulp.dest("./zipped"));

          return stream;
       }));
});

It grabs all the first level contents of ./dist as its source and then pipes it to gulp-foreach.

gulp-foreach looks at each item and I use a plain javascript substr() to get the name of the current item which I store as a variable.

Finally I set a new src using the stored fileName var and pipe the result to gulp-zip using the stored var again as the name of the zipped file.

The result is a structure that looks like this:

proj
proj/dist
proj/dist/sub01
proj/dist/sub02
proj/dist/sub03
proj/zipped
proj/zipped/sub01.zip
proj/zipped/sub02.zip
proj/zipped/sub03.zip

Again, I am a million miles from being an expert but this worked for me and if I understand the question might work for you as well or at least give you some ideas.



标签: gulp