Simplest way to download and unzip files in Node.js cross-platform?

前端 未结 11 1509
一个人的身影
一个人的身影 2020-11-30 23:44

Just looking for a simple solution to downloading and unzipping .zip or .tar.gz files in Node.js on any operating system.

Not sure if this

11条回答
  •  攒了一身酷
    2020-12-01 00:01

    I was looking forward this for a long time, and found no simple working example, but based on these answers I created the downloadAndUnzip() function.

    The usage is quite simple:

    downloadAndUnzip('http://your-domain.com/archive.zip', 'yourfile.xml')
        .then(function (data) {
            console.log(data); // unzipped content of yourfile.xml in root of archive.zip
        })
        .catch(function (err) {
            console.error(err);
        });
    

    And here is the declaration:

    var AdmZip = require('adm-zip');
    var request = require('request');
    
    var downloadAndUnzip = function (url, fileName) {
    
        /**
         * Download a file
         * 
         * @param url
         */
        var download = function (url) {
            return new Promise(function (resolve, reject) {
                request({
                    url: url,
                    method: 'GET',
                    encoding: null
                }, function (err, response, body) {
                    if (err) {
                        return reject(err);
                    }
                    resolve(body);
                });
            });
        };
    
        /**
         * Unzip a Buffer
         * 
         * @param buffer
         * @returns {Promise}
         */
        var unzip = function (buffer) {
            return new Promise(function (resolve, reject) {
    
                var resolved = false;
    
                var zip = new AdmZip(buffer);
                var zipEntries = zip.getEntries(); // an array of ZipEntry records
    
                zipEntries.forEach(function (zipEntry) {
                    if (zipEntry.entryName == fileName) {
                        resolved = true;
                        resolve(zipEntry.getData().toString('utf8'));
                    }
                });
    
                if (!resolved) {
                    reject(new Error('No file found in archive: ' + fileName));
                }
            });
        };
    
    
        return download(url)
            .then(unzip);
    };
    

提交回复
热议问题