How do I rename image file names to match the folder name plus a number?

569 views Asked by At

In Gulp, how do I rename image file names to match the folder name plus a number?

For example, I have:

img/cats/spotty.svg
img/cats/edgar.svg

and I'd like:

images/cats/cat1.svg
images/cats/cat2.svg

I have several other subfolders besides cats as well.

I've tried unsuccessfully to use rename but the addition of numbers makes it not work fully.

1

There are 1 answers

0
Jeroen On BEST ANSWER

You can use the gulp-rename package and provide it with a custom function for renaming your files as they pass through. Use the path package for some utility, create a constructor function to generate a new hashtable of counters, and voila:

'use strict';

var gulp = require('gulp'),
    rename = require('gulp-rename'),
    path = require('path');

gulp.task('default', [], function() {
    var renamer = new Renamer();

    gulp.src('img/**/*.*')
        .pipe(rename(renamer.folderToImgName))
        .pipe(gulp.dest('.build/images'));
});

function Renamer() {
    var countersHashTable = {};

    function folderToImgName(fileInfo) {
        var baseName = path.basename(fileInfo.dirname);

        countersHashTable[baseName] = countersHashTable[baseName] || 1;

        fileInfo.basename = baseName + countersHashTable[baseName].toLocaleString();

        // If you want a flat folder structure:
        //fileInfo.dirname = path.dirname(fileInfo.dirname);

        countersHashTable[baseName]++;
    }

    this.folderToImgName = folderToImgName;
}

Partially remixed from this answer by @OverZaelous.