Search code examples
node.jsstreamrequestunzip

invalid signature error when unzip folder in nodejs


I use unzip node module for unzip my binary-data (come from request module). it fails in some cases when request module's response not contain zip folder binary data (if response is not have zip folder data, some other binary data).

How I handle this exception.

const request = require("request");
const unzip = require('unzip');
const stream = require('stream');

var options = {
        method: 'GET',
        url: /*URL*/,
        encoding: null
    };

    request(options, function (error, response, body) {
        zipExtract(error, body);
    });

zipExtract:

function zipExtract(error, zipData) {
    if (error) {
        console.error(error);
    }
    else {
        try {
            //create stream object
            var artifactStream = new stream.PassThrough();

            //parse buffer into stream
            artifactStream.end(zipData);

            //pipe response to unzip
            artifactStream.pipe(unzip.Extract({path: 'app/output'}));
        }

        catch (exception) {
            console.error(exception);
        }
    }
} 

it prompt error on console

events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: invalid signature: 0x6d74683c
    at C:\app-hub\module-application-size\node_modules\unzip\lib\parse.js:63:13
    at runCallback (timers.js:637:20)
    at tryOnImmediate (timers.js:610:5)
    at processImmediate [as _immediateCallback] (timers.js:582:5)
npm ERR! Test failed.  See above for more details.

Solution

  • use adm-zip module for handle exception.

    const admzip = require('adm-zip');
    
    try {
        var zip = new admzip(zipData);
        zip.extractAllTo(/*path*/);
    
    }
    catch (exception) {
        console.error(exception);
    }