Under my assets/
folder, I have numerous subfolders, each containing an arbitrary number of images, like so:
assets/article1/
assets/article2/
I'm trying to write a gulp task to locate all .jpg
images within and generate their thumbnail versions, to be saved in a thumbs/
subfolder within the folder where each file resides:
assets/article1/ # original jpg images
assets/article1/thumbs/ # thumbnail versions of above..
assets/article2/
assets/article2/thumbs/
I've been trying various approaches but no luck. The closest I've come is:
gulp.task('thumbs', function () {
return gulp.src( './assets/**/*.jpg' )
.pipe( imageResize( { width: 200 } ) )
.pipe( gulp.dest( function( file ) { return file.base + '/thumbs/'; } ) );
});
However, this creates a single thumbs\
folder at the root of assets\
assets/article1/
assets/article2/
assets/thumbs/article1/
assets/thumbs/article2/
Is there a good info on the paths and wildcards anywhere? Clearly I'm not handling it well..
You could use path.dirname
for that: http://nodejs.org/api/path.html#path_path_dirname_p
// require core module
var path = require('path');
gulp.task('thumbs', function () {
return gulp.src( './assets/**/*.jpg' )
.pipe( imageResize( { width: 200 } ) )
.pipe( gulp.dest( function( file ) { return path.join(path.dirname(file.path), 'thumbs'); } ) );
});
Here's what worked for me given the following directory structure (I simplified a bit to focus on just getting the files in the right place)
assets/article1/1.jpg
assets/article2/2.jpg
with a desired outcome of
assets/article1/1.jpg
assets/article1/thumbs/1.jpg
assets/article2/2.jpg
assets/article2/thumbs/2.jpg
Here's what worked for me (modified from this recipe https://github.com/gulpjs/gulp/blob/master/docs/recipes/running-task-steps-per-folder.md)
var gulp = require('gulp'),
rename = require('gulp-rename'),
path = require('path'),
fs = require('fs');
var scriptsPath = 'assets'; // folder to process
function getFolders(dir) {
return fs.readdirSync(dir)
.filter(function(file) {
return fs.statSync(path.join(dir, file)).isDirectory();
});
}
gulp.task('thumbs', function() {
var folders = getFolders(scriptsPath);
return folders.map(function(folder) {
return gulp.src(path.join(scriptsPath, folder, '/**/*.jpg'))
.pipe(rename({dirname: folder + '/thumbs/'}))
.pipe(gulp.dest(scriptsPath));
});
});