2016-01-25 28 views
1

開始索引我想寫所有從一個文件夾中的文件移動到另一個,使用數字改名一飲而盡任務。咕嘟咕嘟,重命名文件 - 從higest號碼文件夾

我到目前爲止這個任務:

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

我想知道我怎麼可以編寫腳本,它會檢查什麼是最高的數字已經在相應的文件夾和更新變種索引,以便文件不會被覆蓋。

回答

2

隨着一飲而盡,我幾乎沒有經驗。我想這可以做得更有效率。我用另一個目錄結構嘗試了它,它適用於我。 首先,你必須要求文件系統模塊,從而把這個在你大口文件的頂部:

const fs = require('fs'); 

下面是修改一飲而盡任務:

/** 
* Gulp task edited by Georgi Naumov 
* [email protected] 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 
* [email protected] 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')); 
}); 

在這裏可以閱讀包的文檔(我剛剛更新的文檔):

https://www.npmjs.com/package/npm-max-dir-index

+0

現在腳本很快,我沒有超過30個文件在af老。我可以想象,如果我到了文件夾有1000個文件的時候,它可能需要一段時間...無論如何,很好的解決方案。謝謝! – TheFullResolution