Javascript 用序号重新命名文件-从文件夹中最高的编号开始索引
我想写一个gulp任务,其中所有文件从一个文件夹移动到另一个文件夹,使用数字重命名 到目前为止,我的任务是:Javascript 用序号重新命名文件-从文件夹中最高的编号开始索引,javascript,npm,gulp,Javascript,Npm,Gulp,我想写一个gulp任务,其中所有文件从一个文件夹移动到另一个文件夹,使用数字重命名 到目前为止,我的任务是: var index = 0; gulp.task("jpg", function () { return gulp.src('img/new/**.{jpg,JPG}') .pipe(chmod(666)) .pipe(rename(function (path) { path.basenam
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 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'));
});
这里可以阅读软件包文档(我刚刚更新了文档):
现在脚本速度很快,我的文件夹中的文件不超过30个。我可以想象,如果我的文件夹有1000个文件,可能需要一段时间。。。无论如何,这是一个很好的解决方案。谢谢