1

So I've got some data that's been compressed with PHP's gzcompress method: http://us2.php.net/manual/en/function.gzcompress.php

How can I decode this data from node.js??

I've tried "compress", "zlib" and several other node compression libraries, but none of them seem to reckognize the data. For example, zlib just gives me "Error: incorrect header check"

Answer: Turns out that "zlib" is the way to go. We had an additional issue with binary data from memcache. If you have binary data in a node.js Buffer object and you call toString() instead of .toString('binary'), it get's all kinds of scrambled as stuff is escaped or escape sequences are interpreted or whatever. Unfortunately, all the memcache plugins I've tried to date assume string data from memcache, and are not disciplined about handling it properly.

Best ZLIB module I've found:

https://github.com/kkaefer/node-zlib

// first run "npm install zlib", then...
var zlib = require('zlib');
var gz = zlib.deflate(new Buffer("Hello World", 'binary')); // also another 'Buffer'
console.log(zlib.inflate(gz).toString('binary'));

FYI, this question is VERY similar to a related question about Java: PHP's gzuncompress function in Java?

Community
  • 1
  • 1
Dave Dopson
  • 41,600
  • 19
  • 95
  • 85

2 Answers2

2

Stealing from another post (Which compression method to use in PHP?)

  • gzencode() uses the fully self-contained gzip format, same as the gzip command line tool
  • gzcompress() uses the raw ZLIB format. It is similar to gzencode but has different header data, etc. I think it was intended for streaming.
  • gzdeflate() uses the raw DEFLATE algorithm on its own, which is the basis for both the other formats.

Thus, "zlib" would be the correct choice. This is NOT cross-compatible with gzip.

Try https://github.com/kkaefer/node-zlib

Community
  • 1
  • 1
Dave Dopson
  • 41,600
  • 19
  • 95
  • 85
  • Note that node.js zlib includes inflateRaw(), so you can deal with the PHP forms with and without the header. – Brian H May 27 '14 at 21:05
0

php:

<?php 
$data = 'HelloWorld';
$gzcompress = gzcompress($data);
$gzcompress_base64_encode = base64_encode($gzcompress);
echo "Compressing: {$data}\n";
echo $gzcompress."\n";
echo $gzcompress_base64_encode."\n";
echo "--- inverse ---\n";
echo gzuncompress(base64_decode($gzcompress_base64_encode))."\n";

nodejs:

const zlib = require('zlib');
var data = 'HelloWorld';
var z1 = zlib.deflateSync( Buffer.from(data));

var gzcompress = z1.toString();
var gzcompress_base64_encode = z1.toString('base64');
console.log('Compressing '+data);
console.log(gzcompress);
console.log(gzcompress_base64_encode);
console.log('--- inverse ---');
console.log(zlib.inflateSync(Buffer.from(gzcompress_base64_encode,'base64')).toString());
  • Hi ColudFrameWork, Please help me. If I have gzcompress, how I can get z1. Input: gzcompress, Output: I want value of z1. Thank you so much – vannguyen Apr 08 '22 at 03:54