NodeJS: zlib.gunzip() on file contents returns Error: incorrect header check

My script takes file data, interprets it, and spits it out in a different format. The user can input a URL or upload a file, and the file refence for either of these can be XML or GZIP (which I then decompress).

What works:

  • Parsing XML + GZIP from URL
  • Uploading files
  • Parsing XML body from uploaded files

What doesn't work

  • Decompressing + parsing GZIP'd body from uploaded files

Whilst zlib.gunzip(fileX_bodyFromUpload) fails, zlib.gunzip(fileX_bodyFromURL) works perfectly. Weirdly, ZLIB gets pissy with the file upload version of the same file, claiming [Error: incorrect header check].

So, how can I get ZLIB to decompress file contents correctly?

Functions:

var tmp_path = req.files.file.path;
fs.readFile(tmp_path, 'utf8', function(err, body) {
    fs.unlink(tmp_path, function(err) { if (err) throw err; });
    prepareBody(req, res, body);
});

function prepareBody(req, res, body) {
    if (req.body.isGzip == 'on') {
        zlib.gunzip(body, function(err, dezipped) {
            if (typeof dezipped != 'undefined') {
                var xmlData = dezipped.toString('utf-8');
                parseAndOffload(req, res, xmlData);
            } else {
                console.log(err);
                console.error("TERMINATING: Could not decompress as GZIP file.");
                res.status(400).send('Could not decompress as GZIP file.')
            }
        });
    } else {
        parseAndOffload(req, res, body);
    }
}

Upload GZIP file -> console log:

 { file:
    { fieldname: 'file',
      originalname: '0c8fae64645fef5bf6f32c494cdde6b2.gz',
      name: 'b95686fb9f205e253c41dd96ccd41c24.gz',
      encoding: '7bit',
      mimetype: 'application/x-gzip',
      path: 'uploads/b95686fb9f205e253c41dd96ccd41c24.gz',
      extension: 'gz',
      size: 35898,
      truncated: false,
      buffer: null } }
 loadFile: 78ms
 { [Error: incorrect header check] errno: -3, code: 'Z_DATA_ERROR' }
 TERMINATING: Could not decompress as GZIP file.

Like in your previous question, fs.readFile is returning a string when you add 'utf8' as the encoding type.

Remove this and readFile will return a buffer, which zlib.gunzip can work with.

fs.readFile(tmp_path, function(err, body) {
    fs.unlink(tmp_path, function(err) { if (err) throw err; });
    prepareBody(req, res, body);
});