`
sillycat
  • 浏览: 2545418 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

NodeJS12 and Zlib

 
阅读更多
NodeJS12 and Zlib

It works as it should be as follow index.js
const zlib = require('zlib');
const input = 'hello carl, how are you?';
zlib.deflate(input, function(err, buffer) {
  if (!err) {
    console.log(buffer.toString('base64'));
  }
});
const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
zlib.unzip(buffer, function(err, buffer) {
  if (!err) {
    console.log(buffer.toString());
  }
});

> node index.js
eJzLSM3JyVdITizK0VHIyC9XSCxKVajML7UHAGvnCIU=
.................................

Convert the callback mode to async await mode
const zlib = require('zlib');

const input = 'hello carl, how are you doing?';

(async () => {
    const output = await new Promise((resolve, reject) => {
            zlib.deflate(input, function(err, buffer) {
              return void err ? reject(err) : resolve(buffer.toString('base64'))
            })
          });
    console.log(output);

    const buffer = Buffer.from(output, 'base64');
   
    const resp = await new Promise((resolve, reject) => {
            zlib.unzip(buffer, function(err, buffer) {
              return void err ? reject(err) : resolve(buffer.toString())
            });
          });
    console.log(resp);
})();


> node index.js
eJzLSM3JyVdITizK0VHIyC9XSCxKVajML1VIyc/MS7cHAKaqCrY=
hello carl, how are you doing?

Handle both gzip data or text data with base64
const zlib = require('zlib');

const input = 'Hello World';
const base64Input = Buffer.from("Hello World").toString('base64');

(async () => {
    const outputZip = await new Promise((resolve, reject) => {
            zlib.deflate(input, function(err, buffer) {
              return void err ? reject(err) : resolve(buffer.toString('base64'))
            })
          });
    console.log(outputZip);

    console.log(base64Input);

    //console.log(Buffer.from("Hello World").toString('base64'));
    //console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString());

    const rawInput = Buffer.from(base64Input, 'base64');
   
    const resp = await new Promise((resolve, reject) => {
            zlib.unzip(rawInput, function(err, buffer) {
              return void err ? reject(err) : resolve(buffer ? buffer.toString() : rawInput.toString());
            });
          });
    console.log(resp);
})();


> node index.js
eJzzSM3JyVcIzy/KSQEAGAsEHQ==
SGVsbG8gV29ybGQ=
Hello World


References:
https://millermedeiros.github.io/mdoc/examples/node_api/doc/zlib.html
https://stackoverflow.com/questions/12148948/how-do-i-ungzip-decompress-a-nodejs-requests-module-gzip-response-body
https://nodejs.org/docs/latest-v12.x/api/zlib.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics