Gulp 如果存在重复项,请将其吞掉
是否可以从源中删除同名文件?例如,假设我有以下文件夹结构Gulp 如果存在重复项,请将其吞掉,gulp,Gulp,是否可以从源中删除同名文件?例如,假设我有以下文件夹结构 a ---file1.txt ---file2.txt ---file3.txt b ---file1.txt 当我选择源文件夹中的两个文件夹时,我只希望目标文件夹中的文件不重复。在上面的例子中,结果是 result ---file2.txt ---file3.txt 可选,如果我能以某种方式复制过滤器并在单独的文件夹中写入,那就太好了。 所谓重复,我的意思是通过名称明确重复,文件内容并不重要。我花了一段时间才达
a
---file1.txt
---file2.txt
---file3.txt
b
---file1.txt
当我选择源文件夹中的两个文件夹时,我只希望目标文件夹中的文件不重复。在上面的例子中,结果是
result
---file2.txt
---file3.txt
可选,如果我能以某种方式复制过滤器并在单独的文件夹中写入,那就太好了。
所谓重复,我的意思是通过名称明确重复,文件内容并不重要。我花了一段时间才达到目的,但请尝试以下方法:
var gulp = require('gulp');
var fs = require('fs');
var path = require('path');
var flatten = require('gulp-flatten');
var filter = require('gulp-filter');
var folders = ['a', 'b', 'c']; // I just hard-coded your folders here
// this function is called by filter for each file in the above folders
// it should return false if the file is a duplicate, i.e., occurs
// in at least two folders
function isUnique(file) {
console.dir(file.history[0]); // just for fun
var baseName = file.history[0].split(path.sep);
baseName = baseName[baseName.length - 1];
// var fileParents = '././';
var fileParents = '.' + path.sep + '.' + path.sep;
var count = 0;
folders.forEach(function (folder) {
if (fs.existsSync(fileParents + folder + path.sep + baseName)) count++;
// could quit forEach when count >= 2 if there were a lot of folders/files
// but there is no way to break out of a forEach
});
if (count >= 2) { // the file is a duplicate
fs.unlinkSync(file.history[0]); // remove from 'Result' directory
return false;
}
else return true;
}
gulp.task('default', ['clump'], function () {
// create a filter to remove duplicates
const f = filter(function (file) { return isUnique(file); }, {restore: true, passthrough: false} );
const stream = gulp.src('./result/*.txt')
.pipe(f); // actually do the filtering here
f.restore.pipe(gulp.dest('duplicates')); // new stream with the removed duplicates
return stream;
});
// 'clump' runs first
// gathers all files into result directory
gulp.task('clump', function () {
return gulp.src('./**/*.txt')
.pipe(flatten()) // because the original folder structure in not wanted
.pipe(gulp.dest('result'));
});
大口喝一口。默认任务将首先触发“集群”任务
由于您的OP不要求保留任何特定版本的复制文件,比如最新版本或其他版本,所以我在这里不担心这一点。如果在“Result”文件夹中,您需要复制文件的每个版本,例如一个文件夹中的file1.txt版本和另一个文件夹中的file1.txt版本,但显然必须重命名为可以在“clump”任务中执行的操作
让我知道这是否适合你