programing

Node.js를 사용하여 전체 디렉토리를 압축해야합니다.

nasanasas 2020. 10. 14. 07:52
반응형

Node.js를 사용하여 전체 디렉토리를 압축해야합니다.


Node.js를 사용하여 전체 디렉토리를 압축해야합니다. 저는 현재 node-zip을 사용하고 있으며 프로세스가 실행될 때마다 잘못된 ZIP 파일을 생성합니다 ( 이 Github 문제 에서 볼 수 있듯이 ).

디렉토리를 압축 할 수있는 또 다른 더 나은 Node.js 옵션이 있습니까?

편집 : 아카이버 를 사용하여 끝났습니다.

writeZip = function(dir,name) {
var zip = new JSZip(),
    code = zip.folder(dir),
    output = zip.generate(),
    filename = ['jsd-',name,'.zip'].join('');

fs.writeFileSync(baseDir + filename, output);
console.log('creating ' + filename);
};

매개 변수의 샘플 값 :

dir = /tmp/jsd-<randomstring>/
name = <randomstring>

업데이트 : 내가 사용한 구현에 대해 묻는 사람들 을 위해 내 다운로더에 대한 링크가 있습니다 .


결국 아카이버 lib 를 사용하게되었습니다 . 잘 작동합니다.

var file_system = require('fs');
var archiver = require('archiver');

var output = file_system.createWriteStream('target.zip');
var archive = archiver('zip');

output.on('close', function () {
    console.log(archive.pointer() + ' total bytes');
    console.log('archiver has been finalized and the output file descriptor has closed.');
});

archive.on('error', function(err){
    throw err;
});

archive.pipe(output);
archive.bulk([
    { expand: true, cwd: 'source', src: ['**'], dest: 'source'}
]);
archive.finalize();

나는 새로운 것을 보여주는 척하지 않고 (나와 같은) 코드에서 Promise 함수를 사용하는 것을 좋아하는 사람들을 위해 위의 솔루션을 요약하고 싶습니다.

const archiver = require('archiver');

/**
 * @param {String} source
 * @param {String} out
 * @returns {Promise}
 */
function zipDirectory(source, out) {
  const archive = archiver('zip', { zlib: { level: 9 }});
  const stream = fs.createWriteStream(out);

  return new Promise((resolve, reject) => {
    archive
      .directory(source, false)
      .on('error', err => reject(err))
      .pipe(stream)
    ;

    stream.on('close', () => resolve());
    archive.finalize();
  });
}

누군가를 도울 수 있기를 바랍니다.)


모든 파일 및 디렉토리를 포함하려면 :

archive.bulk([
  {
    expand: true,
    cwd: "temp/freewheel-bvi-120",
    src: ["**/*"],
    dot: true
  }
]);

It uses node-glob(https://github.com/isaacs/node-glob) underneath, so any matching expression compatible with that will work.


Archive.bulk is now deprecated, the new method to be used for this is glob:

var fileName =   'zipOutput.zip'
var fileOutput = fs.createWriteStream(fileName);

fileOutput.on('close', function () {
    console.log(archive.pointer() + ' total bytes');
    console.log('archiver has been finalized and the output file descriptor has closed.');
});

archive.pipe(fileOutput);
archive.glob("../dist/**/*"); //some glob pattern here
archive.glob("../dist/.htaccess"); //another glob pattern
// add as many as you like
archive.on('error', function(err){
    throw err;
});
archive.finalize();

This is another library which zips the folder in one line : zip-local

var zipper = require('zip-local');

zipper.sync.zip("./hello/world/").compress().save("pack.zip");

Use Node's native child_process api to accomplish this.

No need for third party libs. Two lines of code.

const child_process = require("child_process");
child_process.execSync(`zip -r DESIRED_NAME_OF_ZIP_FILE_HERE *`, {
  cwd: PATH_TO_FOLDER_YOU_WANT_ZIPPED_HERE
});

I'm using the synchronous API. You can use child_process.exec(path, options, callback) if you need async. There are a lot more options than just specifying the CWD to further finetune your requests. See exec/execSync docs.


Please note: This example assumes you have the zip utility installed on your system (it comes with OSX, at least). Some operating systems may not have utility installed (i.e., AWS Lambda runtime doesn't). In that case, you can easily obtain the zip utility binary here and package it along with your application source code (for AWS Lambda you can package it in a Lambda Layer as well), or you'll have to either use a third party module (of which there are plenty on NPM). I prefer the former approach, as the ZIP utility is tried and tested for decades.


Adm-zip has problems just compressing an existing archive https://github.com/cthackers/adm-zip/issues/64 as well as corruption with compressing binary files.

I've also ran into compression corruption issues with node-zip https://github.com/daraosn/node-zip/issues/4

node-archiver is the only one that seems to work well to compress but it doesn't have any uncompress functionality.


To pipe the result to the response object (scenarios where there is a need to download the zip rather than store locally)

 archive.pipe(res);

Sam's hints for accessing the content of the directory worked for me.

src: ["**/*"]

I have found this small library that encapsulates what you need.

npm install zip-a-folder

const zip-a-folder = require('zip-a-folder');
await zip-a-folder.zip('/path/to/the/folder', '/path/to/archive.zip');

https://www.npmjs.com/package/zip-a-folder


You can try in a simple way:

Install zip-dir :

npm install zip-dir

and use it

var zipdir = require('zip-dir');

let foldername =  src_path.split('/').pop() 
    zipdir(<<src_path>>, { saveTo: 'demo.zip' }, function (err, buffer) {

    });

참고URL : https://stackoverflow.com/questions/15641243/need-to-zip-an-entire-directory-using-node-js

반응형