Handle multiple files in a Gulp plugin

2019-09-04 07:25发布

问题:

I am trying to write a gulp plugin. You use it like this:

var gulp = require('gulp'),
    codo = require('gulp-codo');

gulp.task('doc', function () {
    return gulp.src('*.coffee')
    .pipe(codo()) // codo(name, title, readme, dir)
});

I want *.coffee to provide all the coffeescript files in the current directory to codo().

In the plugin the input is handled like so:

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

     invokeCodo(file.path, name, title, readme, dir, function(err, data) {
         if(err) {
            cb(new gutil.PluginError('gulp-codo', err, {fileName: file.path}));
            return;
         }
         file.contents = new Buffer(data);
         cb(null, file);
    });
});

I noticed that file.path is only the first wildcard match and not all the matches. How can I loop this for each match. I tried search here, but only found questions relating to generating mutiple outputs in a Gulp plugin.

Thanks.

回答1:

gulp-foreach might help you. Your task should then look something like this:

gulp.task('doc', function () {
    return gulp.src('*.coffee')
        .pipe(foreach(function(stream, file){
            return stream
                .pipe(codo()) // codo(name, title, readme, dir)
                .pipe(concat(file.name));
        });
});

Also, do not forget to include gulp-foreach like this at the top of your file:

var foreach = require('gulp-foreach');