[英]Gulp-rename: get original file path
I'm using gulp-rename to rename files. 我正在用gulp-rename重命名文件。
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. rename
方法会迭代每个文件的回调。
This callback takes object path
as argument, which is contains dirname
property. 此回调将对象
path
作为参数,其中包含dirname
属性。
But path.dirname
has value '.'
但是
path.dirname
值为'.'
, instead of original file path like a '/dir/a/style.css'
. ,而不是像
'/dir/a/style.css'
这样的原始文件路径。
So, my question is how can I get initial file path inside of rename
callback? 所以,我的问题是如何在
rename
回调中获取初始文件路径?
From the gulp-rename docs : 从gulp重命名docs :
dirname is the relative path from the base directory set by gulp.src to the filename.
dirname是从gulp.src设置的基本目录到文件名的相对路径。
And 和
dirname is the remaining directories or ./ if none.
dirname是其余目录;如果没有,则为./。
So you may need to use a glob ( /*/
) to make sure it gives you the extra path information in dirname
. 因此,您可能需要使用glob(
/*/
)来确保它在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 ). 如果
gulp.src('/dir/*/style.css', {base: '/'})
也可以尝试gulp.src('/dir/*/style.css', {base: '/'})
(请参阅gulp.src docs )。
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'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.