我想将Gulp和gulp-zip用于:
./lessons/
文件夹的每个子文件夹./lessons/1-hermit-crab/
应该命名为1-hermit-crab.zip
。./lessons/
文件夹中。我从这里开始,但是由于无法获取压缩目录的名称而陷入困境,因此我可以将其用作存档名称。所以我现在将档案保存在子文件夹中。
感谢您的帮助。
gulp.task('zip-lessons', function() {
// Get an array of subdirectories under ./lessons/
var subDirectories = glob.sync('./lessons/*/');
// For each directory…
subDirectories.forEach(function (subDirectory) {
return gulp.src(subDirectory + '**')
.pipe(zip('lesson.zip'))
.pipe(gulp.dest(subDirectory));
});
});
答案 0 :(得分:2)
您可以使用节点的path
模块来获取子目录的名称,如下所示:
const path = require('path');
const dirName = path.parse('./folderA/folderB').base // -> 'folderB'
并将dirName传递给zip()
:
const { task, src, dest } = require('gulp');
const path = require('path');
const zip = require('gulp-zip');
const glob = require('glob');
const subDirs = glob.sync('./lessons/*');
task('zipLessions', (done) => {
subDirs.forEach(subDir => {
const dirName = path.parse(subDir).base;
src(subDir + '/*')
.pipe(zip(`${dirName}.zip`))
.pipe(dest('./lessons'))
})
done()
})
答案 1 :(得分:-1)
我的同事为我提供了这个可行的解决方案,所以现在我正在使用它。
const gulp = require('gulp');
const zip = require('gulp-zip');
var fs = require('fs');
var path = require('path');
// Functions
function getFolders(dir) {
return fs.readdirSync(dir)
.filter(function(file) {
return fs.statSync(path.join(dir, file)).isDirectory();
});
}
// Tasks
// Zip each folder in /lessons and place the archive in the /lessons root
gulp.task('zip-lessons', () => {
let folders = getFolders('lessons/');
console.log(folders)
var tasks = folders.map(function(folder) {
gulp.src(`lessons/${folder}/**`)
.pipe(zip(`${folder}.zip`))
.pipe(gulp.dest('lessons'))
})
});