[英]Gulp-rename files with ordinal numbers - starting index from the higest number in folder
我想編寫一個gulp任務,其中所有文件從一個文件夾移動到另一個文件夾,並使用數字重命名。
到目前為止,我有以下任務:
var index = 0;
gulp.task("jpg", function () {
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'));
});
我想知道如何編寫腳本來檢查文件夾中已有的最高編號,並相應地更新var索引,這樣文件就不會被覆蓋。
我幾乎沒有經驗。 我想它可以更有效地完成。 我嘗試了另一種目錄結構,它對我有用。 首先,您必須需要文件系統模塊,因此請將其放在gulp文件的頂部:
const fs = require('fs');
這是修改后的gulp任務:
/**
* Gulp task edited by Georgi Naumov
* gonaumov@gmail.com for contacts
* and suggestions.
*/
gulp.task("jpg", function () {
var files = fs.readdirSync('img/gallery/full_size/'), index = 0;
// here we will find maximum number of index
// keep in mind that this is very inefficient.
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'));
});
如果在這種情況下性能很重要,我們可以執行shell命令,該命令可以使用最大數量的文件,但是任務將不再與平台無關。
編輯:
我認為隔離邏輯以在程序包中找到最大數量是一個好主意。 所以我剛剛發布了npm包。 您可以安裝和使用它。
對於安裝,您必須使用:
npm install --save npm-max-dir-index
之后,您可以通過以下方式使用它:
const maxDirIndex = require('npm-max-dir-index');
/**
* Gulp task edited by Georgi Naumov
* gonaumov@gmail.com 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'));
});
這里可以閱讀軟件包文檔(我剛剛更新了文檔):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.