从保留文件结构的文件夹创建一个 zip,包括父文件夹(和单个文件)

Create a zip from folders retaining file structure including parent folders (and single files)

我正在尝试从以下文件结构创建一个 zip 文件:

-dist/bundle.js
-assets/[several subfolders with files]
-config.json
-bootstrap.js

我用过gulp-zip:

gulp.task('zip', ()=>{
return gulp.src(['dist/**/*.*', 'assets/**/*.*','config.json', 'bootstrap.js'])
    .pipe(zip('game.zip'))
    .pipe(gulp.dest('deploy'))
})

结果是: game.zip 结构如下:

-game
--[some assets subfolder]
--[other assets subfolder]
--[third assets subfolder]
--bundle.js
--bootstrap.js
--config.json

files/folders不应该在文件夹(游戏)中,而是保留它们最初的结构,assets 和 dist 文件夹也应该在结构中。 我可以从 package.json 脚本节点 运行 获得的任何解决方案都将受到欢迎。 (gulp/webpack/grunt/whatever)

谢谢!

我试过这个:

gulp.task('default', ()=>{
  return gulp.src(['dist/**/*.*', 'assets/**/*.*','config.json', 'bootstrap.js'], {base: '.'})
      .pipe(zip('game.zip'))
      .pipe(gulp.dest('deploy'))
})

只需将 {base: '.'} 选项添加到 gulp.src 即可满足您的需求。参见 gulp base option。使用 {base: '.'} 基本上告诉 gulp 使用 dest 位置中的所有目录。否则默认操作是删除 glob 之前的目录。因此,在“dist/**/*.*”中,如果没有基本选项,dist 文件夹将不会保留。

我不知道你从哪里得到一个 game 文件夹,我从来不知道。

只是想 post 我在网上搜索时找到的另一个解决方案(仍然接受 解决方案,因为它很多 shorter/simpler:

const fs = require('fs');
const archiver = require('archiver');

const output = fs.createWriteStream(__dirname + '/deploy/rosa.zip');
const archive = archiver('zip', {
store: true
//zlib: { level: 9 } // Sets the compression level.
});

// listen for all archive data to be written
// 'close' event is fired only when a file descriptor is involved
output.on('close', function() {
console.log(archive.pointer() + ' total bytes');
console.log('archiver has been finalized and the output file descriptor has 
closed.');
});

// This event is fired when the data source is drained no matter what was the 
data source.
// It is not part of this library but rather from the NodeJS Stream API.
// @see: https://nodejs.org/api/stream.html#stream_event_end
output.on('end', function() {
console.log('Data has been drained');
});

// good practice to catch warnings (ie stat failures and other non-blocking 
errors)
archive.on('warning', function(err) {
if (err.code === 'ENOENT') {
  // log warning
} else {
  // throw error
  throw err;
}
});

// good practice to catch this error explicitly
archive.on('error', function(err) {
throw err;
});
// pipe archive data to the file
archive.pipe(output);

archive.directory('assets/', 'assets');
archive.directory('dist/', 'dist');
archive.file('bootstrap.js', {name: 'bootstrap.js'});
archive.file('config.json', {name: 'config.json'});
archive.finalize();

发件人:Archiver js Docs