My experience with gulp is limited, but I believe there are more efficient ways to utilize it. I experimented with a different directory structure and managed to make it work for me.
Firstly, you need to require the file system module by adding this line at the top of your gulp file:
const fs = require('fs');
Below is the revised gulp task:
/**
* Gulp task modified by Georgi Naumov
* <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcdbd3d2ddc9d1d3cafcdbd1ddd5d092dfd3d1">[email protected]</a> for contacts
* and suggestions.
*/
gulp.task("jpg", function () {
var files = fs.readdirSync('img/gallery/full_size/'), index = 0;
// Finding the maximum index inefficiently
files.forEach(function (currentFile) {
var currentIndex = (/^([0-9]+)\.jpg$/i.exec(currentFile) || [, false])[1];
if (currentIndex && parseInt(currentIndex) >= index) {
index = ++currentIndex;
}
});
return gulp.src('img/new/**.{jpg,JPG}')
.pipe(chmod(666))
.pipe(rename(function (path) {
path.basename = (index++);
path.dirname += "/full_size";
path.extname = ".jpg";
return path;
}))
.pipe(gulp.dest('img/gallery'));
});
If performance is crucial, a shell command could be used to fetch the file with the highest number, but this would sacrifice platform independence.
Edit:
I believe isolating the logic to find the maximum number into a package is a good approach. Therefore, I have created an npm package which can be installed and utilized.
To install, run:
npm install --save npm-max-dir-index
After installation, you can incorporate it as follows:
const maxDirIndex = require('npm-max-dir-index');
/**
* Gulp task modified by Georgi Naumov
* <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e5edece3f7efedf4c2e5efe3ebeeace1edef">[email protected]</a> for contacts
* and suggestions.
*/
gulp.task("jpg", function () {
var index = maxDirIndex('img/gallery/full_size/', '^([0-9]+)\.jpg$');
return gulp.src('img/new/**.{jpg,JPG}')
.pipe(chmod(666))
.pipe(rename(function (path) {
path.basename = (index++);
path.dirname += "/full_size";
path.extname = ".jpg";
return path;
}))
.pipe(gulp.dest('img/gallery'));
});
Please refer to the updated package documentation here:
https://www.npmjs.com/package/npm-max-dir-index