Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten glob down to one directory

Tags:

node.js

gulp

Within Gulp, I am using gulp.src to select every font file from a directory:

gulp.task('copy-fonts', function() {
   gulp.src('components/**/*.{ttf,woff,eof,svg}')
   .pipe(gulp.dest('build/fonts'));
});

However, I would like to have all of these font files wind up in one directory side-by-side rather than have the entire tree re-created from the components directory.

Looking in the Gulp, Gulp Utils, and npm-glob APIs didn't really help me, though I could've easily skipped by it.

What would the best way to go about this?

like image 660
Mark Avatar asked Jan 16 '14 04:01

Mark


3 Answers

I would use gulp-flatten:

var flatten = require('gulp-flatten');
gulp.task('copy-fonts', function() {
  gulp.src('dependencies/**/*.{ttf,woff,eof,svg}')
  .pipe(flatten())
 .pipe(gulp.dest('build/fonts'));
});

As to how this is done internally, check: https://github.com/armed/gulp-flatten/blob/master/index.js

like image 69
Mangled Deutz Avatar answered Oct 02 '22 04:10

Mangled Deutz


Another option is to simply rewrite the file path inside gulp.dest:

var path = require('path');
gulp.task('copy-fonts', function() {
    return gulp.src('components/**/*.{ttf,woff,eof,svg}')
        .pipe(gulp.dest(function(file) {
            file.path = file.base + path.basename(file.path);
            return 'build/fonts';
        }));
});

You can also use this technique with gulp-changed:

var path = require('path');
var changed = require('gulp-changed');

gulp.task('copy-fonts', function() {
  var dest = 'build/fonts';
  return gulp.src('components/**/*.{ttf,woff,eof,svg}')
    .pipe(changed(function(file) {
      file.path = file.base + path.basename(file.path);
      return dest;
    }))
    .pipe(gulp.dest(dest));
});
like image 25
daviestar Avatar answered Oct 02 '22 04:10

daviestar


Another option is to use the glob library to unglob your paths, and then pass the file paths into gulp.src. When gulp src receives unglobbed file paths the relative dir is not maintained and simply copies the file to the root of the dest dir you specify. It can also be useful to unglob your paths first if you need to do any custom filtering or appending before setting src.

glob = require('glob');
gulp.task('copy-fonts', function() {
  files = glob.sync('dependencies/**/*.{ttf,woff,eof,svg}');

  gulp.src(files)
  .pipe(gulp.dest('build/fonts'));
});
like image 28
Corban Brook Avatar answered Oct 02 '22 05:10

Corban Brook