How to Zip files using JavaScript?

后端 未结 6 1458
不知归路
不知归路 2020-12-09 08:29

Is there a way to zip files using JavaScript?? For an example, like in Yahoo mail, when you chose to download all the attachments from an email, it gets zipped and downloade

6条回答
  •  一整个雨季
    2020-12-09 08:49

    I'd recommend going straight to using Node's built-in library Zlib for this, which includes images; encode in base 64 using "buffers". Rather than using npm packages. Reasons being:

    • Zlib is a Node native library - has been kept up-to-date for nearly 10 years now - so the proofs there for long-term supports
    • Node allows you work with Buffers - i.e. you can convert your text string/images to the raw binary data and compress it that way with Zlib
    • Easily compress and decompress large files - leverage node streams to compress files in MBs or GBs

    The fact you are using jszip, would allow me to guess that you are using npm as well as node; assumes you have set up your environment correctly, i.e. node installed globally.

    Example: input.txt compressed to become input.txt.gz

    const zlib = require('zlib');
    const fs = require('fs');
    const gzip = zlib.createGzip();
    const input = fs.createReadStream('input.txt');
    const output = fs.createWriteStream('input.txt.gz');
    
    input.pipe(gzip).pipe(output);
    

    Step 1: So you require each of the native modules from node - require is part of ES5. Zlib as previously mentioned, and fs module, the File System module.

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

    Step 2: The fs module, this allows you to create a readstream, are specifically called to read chunks of data. This will return a readstream object; readable stream

    const input = fs.createReadStream(FILE PATH HERE);
    

    __Note: This readstream object then gets piped again; this chaining of pipes on readsteam objects can occur endlessly, making pipes very flexible.

    ReadStream.pipe(DoesSomething).pipe(SomethingElse).pipe(ConvertToWriteStream)
    

    Step 3: The readstream object, that has been piped and compressed is then converted to writestream object.

    const output = fs.createWriteStream('input.txt.gz');
    
    input.pipe(gzip).pipe(output); // returned filename input.txt.gz, within local directory
    

    So this library allows you easily enter a file path and decide where you want your compressed file to be. You can also choose to do the reverse, if need be.

提交回复
热议问题