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

时间:2018-09-24 07:23:32

标签: gulp zip glob directory-structure gulp-zip

我正在尝试通过以下文件结构创建一个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

文件/文件夹不应位于文件夹(游戏)中,而应保留它们最初具有的结构,资产和dist文件夹也应位于结构中。 我可以从package.json脚本节点运行的任何解决方案都将受到欢迎。 (gulp / webpack / grunt /其他)

谢谢!

2 个答案:

答案 0 :(得分:0)

我尝试过:

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

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

我不知道您在哪里获得game文件夹,我从不知道。

答案 1 :(得分:0)

只想发布我在搜索网络时发现的另一种解决方案(仍然接受Mark's解决方案,因为它更短/更简单:

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