Reputation: 2688
I'm using gulp-rename to rename files.
I want to get files from few directories and put 'em into output directory with some postfix.
This postfix depends on original directory name:
['/dir/a/style.css', '/dir/b/style.css', '/dir/c/style.css']
=>['/output/style_a.css', '/output/style_b.css', '/output/style_c.css']
I do something like this:
var gulp = require('gulp'),
rename = require('gulp-rename'),
files_list = [
'/dir/a/style.css',
'/dir/b/style.css',
'/dir/c/style.css'
];
gulp.src(files_list)
.pipe(rename(function(path) {
// extract dir letter:
var dir_letter = path.dirname.split('dir/')[1].split('/')[0];
// rename file by changing "path" object:
path.basename += '_' + dir_letter;
}))
.pipe(gulp.dest('/output'));
Method rename
iterates callback for each file.
This callback takes object path
as argument, which is contains dirname
property.
But path.dirname
has value '.'
, instead of original file path like a '/dir/a/style.css'
.
So, my question is how can I get initial file path inside of rename
callback?
Upvotes: 0
Views: 1666
Reputation: 1156
From the gulp-rename docs:
dirname is the relative path from the base directory set by gulp.src to the filename.
And
dirname is the remaining directories or ./ if none.
So you may need to use a glob (/*/
) to make sure it gives you the extra path information in dirname
.
var gulp = require('gulp'),
rename = require('gulp-rename');
gulp.src('/dir/*/style.css')
.pipe(rename(function(path) {
// extract dir letter:
var dir_letter = path.split('dir/')[1].split('/')[0];
// rename file by changing "path" object:
path.basename += '_' + dir_letter;
}))
.pipe(gulp.dest('/output'));
You could also try gulp.src('/dir/*/style.css', {base: '/'})
if that does not work (see gulp.src docs).
Upvotes: -1
Reputation: 861
You can use a new stream to get the path.
var Stream = require('stream');
var fileName = '';
function getFileName() {
var stream = new Stream.Transform({ objectMode: true });
stream._transform = function(file, unused, callback) {
fileName = file.path;
callback(null, file);
};
return stream;
}
then you can get the file path in rename stream.
gulp.src('/dir/*/style.css')
.pipe(getFileName(fileName))
.pipe(rename(function(path) {
console.log(fileName);
}))
.pipe(gulp.dest('/output'));
Upvotes: -1