简体   繁体   中英

Gulp-rename: get original file path

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?

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 ).

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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM