在我的assets/
文件夹下,我有很多子文件夹,每个子文件夹包含任意数量的图像,如下所示:
assets/article1/
assets/article2/
我正在尝试编写一个gulp任务来查找其中的所有.jpg
图像并生成其缩略图版本,以保存在每个文件所在的文件夹中的thumbs/
子文件夹中:
assets/article1/ # original jpg images
assets/article1/thumbs/ # thumbnail versions of above..
assets/article2/
assets/article2/thumbs/
我一直在尝试各种方法,但没有运气。我最接近的是:
gulp.task('thumbs', function () {
return gulp.src( './assets/**/*.jpg' )
.pipe( imageResize( { width: 200 } ) )
.pipe( gulp.dest( function( file ) { return file.base + '/thumbs/'; } ) );
});
但是,这会在thumbs\
assets\
文件夹
assets/article1/
assets/article2/
assets/thumbs/article1/
assets/thumbs/article2/
路径和通配符在哪里有很好的信息吗?显然,我处理不好......
答案 0 :(得分:7)
您可以使用path.dirname
: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'); } ) );
});
答案 1 :(得分:2)
这里有什么对我有用,给出了以下目录结构(我简化了一点,专注于将文件放在正确的位置)
assets/article1/1.jpg
assets/article2/2.jpg
具有期望的结果
assets/article1/1.jpg
assets/article1/thumbs/1.jpg
assets/article2/2.jpg
assets/article2/thumbs/2.jpg
这里有什么对我有用(从这个食谱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));
});
});
答案 2 :(得分:0)
我发现了另一种方法,可能对搜索此帖子的人有用。 我最初的目标与您的要求非常相似,并且可以针对几乎任何特定需求调整此方法。
function scss(cb) {
src('./*/scss/*.scss')
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(rename({extname: '.min.css'}))
.pipe(tap(function(file) {
//Enrich the file with crucial information about it's original path, you can save anything you may need. In my case filename is quite enough. It's important to move this block before any sourcemap write if you've any.
file.name = path.basename(file.path);
}))
.pipe(sourcemaps.write('.'))
.pipe(flatten()) //Remove file relative paths.
.pipe(dest(
function( file ) {
//Reconstruct final path using insight we saved before, and using a clean base path provided by flatten.
return path.join(path.dirname(file.path), file.name.replace(/\.min\..+$/, ''), 'static');
}));
cb();
}