如何在 gulp 中压缩生成多个 .zip 文件的多个文件夹? [英] How to zip multiple folders generating multiple .zip files in gulp?

查看:40
本文介绍了如何在 gulp 中压缩生成多个 .zip 文件的多个文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件夹结构如下:

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

对于 projects 中的每个文件夹(proj1、proj2 和 proj3),我想压缩每个文件夹的内容并生成 proj1.zipproj2./zips 文件夹中的 zipproj3.zip.

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.

以下示例函数从 proj1 文件夹生成单个 zip 文件

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'));
});

但是我如何为项目中的每个文件夹执行这样的任务呢?我可以通过 gulp.src('./projects/*') 来压缩所有文件夹,但是接下来呢?

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?

推荐答案

我知道的老问题,我对 gulp 还很陌生,所以这可能被认为是一个 hack,但我一直在尝试做你所追求的,我结束了解决这个问题.

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;
       }));
});

它抓取 ./dist 的所有第一级内容作为其源,然后将其通过管道传输到 gulp-foreach.

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

gulp-foreach 查看每个项目,然后我使用普通的 javascript substr() 来获取我存储为变量的当前项目的名称.

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.

最后,我使用存储的 fileName var 设置了一个新的 src 并将结果通过管道传送到 gulp-zip 再次使用存储的 var 作为压缩文件的名称.

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.

结果是这样的结构:

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 中压缩生成多个 .zip 文件的多个文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆