MattV
MattV

Reputation: 1383

Use filename from earlier gulp.src in gulp.rename() call

I have a zip-file in a folder, I want to extract one of its (zipped) files and give it a filename pattern source file basename + .xml in folder ./sourcefiles_unpacked/

./sourcefiles/test.zip

=>

./sourcefiles/test.zip
./sourcefiles_unpacked/test.xml

Unzipping & filtering works nicely with gulp-unzip, however I'm not sure how to access the filename from the gulp.src call.

gulp.task('unzip-filtered-rename', function() {
  return gulp.src(paths.unzip_sourcefiles)
    // .pipe(debug())
    .pipe(plumber({
      errorHandler: notify.onError('unzip-filtered-rename error: <%= error.message %>')
    }))
    .pipe(changed(paths.excel_targetdir_local_glob, {
      extension: '.xml'
    }))
    .pipe(unzip({filter : function(entry){return minimatch(entry.path, "contents.xml")}}))
    .pipe(gulp.rename(function(path){       

        // ? What do I put here to rename each target file to 
        // ?   its originating zip file's basename?


    })) //   "==> test.xml",
    .pipe(gulp.dest(paths.sourcefiles_unpacked)) //   sourcefiles_unpacked: "./sourcefiles_unpacked/"
});

As soon as gulp.rename() is called the chunk has been renamed to its name as in the zipfile.

Upvotes: 1

Views: 682

Answers (1)

Mark
Mark

Reputation: 181160

Try this:

const glob = require("glob");
const zipFiles = glob.sync('sourcefiles/*.zip');

gulp.task('unzip-filtered-rename', function (done) {

  zipFiles.forEach(function (zipFile) {

    const zipFileBase = path.parse(zipFile).name;

    return gulp.src(zipFile)
        // .pipe(debug())
        //   .pipe(plumber({
        //     errorHandler: notify.onError('unzip-filtered-rename error: <%= error.message %>')
        //   }))
        //   .pipe(changed(paths.excel_targetdir_local_glob, {
        //     extension: '.xml'
        //   }))
        //   .pipe(unzip({filter : function(entry){return minimatch(entry.path, "contents.xml")}}))
        .pipe(rename({
            basename: zipFileBase,
        }))
        .pipe(gulp.dest("./sourcefiles_unpacked")) //   sourcefiles_unpacked: "./sourcefiles_unpacked/"
    });
    done();
});

I commented out the other stuff you do just for testing purposes. Running each file through a forEach or map allows you to set a variable at the beginning outside of the stream that will be available in the following stream.

Also see How to unzip multiple files in the same folder with Gulp for more discussion on setting variables to be used in a stream.

Upvotes: 2

Related Questions