简体   繁体   中英

Grouping files by ignoring file extension in gulp

Assuming the following list of files

file1.csv
file2.csv
file2.js

a standard gulp task may look like this

gulp.task( 'exampleTask', function() {
  return gulp.src([ '*.json', '*.csv', '*.js' ])
    .pipe( gulpModule() )
    .pipe( gulp.dest( '/dest/' ) );
});

Using that setup each of the three files will get piped through gulpModule() .

My requirement, however, is slightly different: If the file extension is not .js and the same filename exists just with a .js extension, then do not pipe the current file along.

So in the above example, only the following files would get piped through gulpModule() :

file1.csv
file2.js

Any idea how to achieve this?

You should be able to do this with a simple plugin, as demonstrated below.

  1. In the plugin, inspect your file name and run your business rules.
  2. If the file meets the parameters, pass it along with this.push()

var through = require('through2');
var path = require("path");

gulp.task( 'exampleTask', function() {
      return gulp.src([ '*.json', '*.csv', '*.js' ])
        .pipe(exclude())
        .pipe( gulpModule() )
        .pipe( gulp.dest( '/dest/' ) );
    });


    var exclude = function() {

        return through.obj(function (file, enc, callback) {     

                var ext = path.extname(file.path),
                  filePath = file.path.substring(0,file.path.length-ext.length);

                if (ext!=".js" &&  !fs.existsSync(filePath + ".js") ) 
                {
                    //push it, otherwise ignore it.
                    this.push(file);
                }     

            return callback();
        });

    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM