Generating a file per folder

If you have a set of folders, and wish to perform a set of tasks on each, for instance...


...and want to end up with...

/scripts/angularjs.min.js'll need to do something like the following...

var fs = require('fs');
var path = require('path');
var merge = require('merge-stream');
var gulp = require('gulp');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');

var scriptsPath = 'src/scripts';

function getFolders(dir) {
    return fs.readdirSync(dir)
      .filter(function(file) {
        return fs.statSync(path.join(dir, file)).isDirectory();

gulp.task('scripts', function() {
   var folders = getFolders(scriptsPath);

   var tasks = {
      return gulp.src(path.join(scriptsPath, folder, '/**/*.js'))
        // concat into foldername.js
        .pipe(concat(folder + '.js'))
        // write to output
        // minify
        // rename to folder.min.js
        .pipe(rename(folder + '.min.js')) 
        // write to output again

   // process all remaining files in scriptsPath root into main.js and main.min.js files
   var root = gulp.src(path.join(scriptsPath, '/*.js'))

   return merge(tasks, root);

A few notes:

  • - executes the function once per folder, and returns the async stream
  • merge - combines the streams and ends only when all streams emitted end
Last Updated: 7/6/2016, 1:47:30 PM