zlib.gzip()方法是Zlib模塊的內置應用程序編程接口,用於壓縮大量數據。
用法:
zlib.gzip( buffer, options, callback )
參數:此方法接受上述和以下所述的三個參數:
- buffer:它可以是Buffer,TypedArray,DataView,ArrayBuffer和字符串的類型。
 - options:它是一個可選參數,其中包含zlib選項。
 - callback:它包含回調函數。
 
返回值:壓縮後返回數據塊。
以下示例說明了Node.js中zlib.gzip()方法的使用:
範例1:
// Node.js program to demonstrate the      
// gzip() method 
  
// Including zlib module 
const zlib = require("zlib"); 
  
// Declaring input and assigning 
// it a value string 
var input = "Geek"; 
  
// Calling gzip method 
zlib.gzip(input, (err, buffer) => { 
  
  if (!err) { 
  
    console.log(buffer.toString('base64')); 
  }  
  else { 
    console.log(err); 
  } 
}); 
console.log("Data Compressed...");輸出:
Data Compressed... H4sIAAAAAAAAA3NPTc0GAGGRcasEAAAA
範例2:
// Node.js program to demonstrate the      
// gzip() method 
  
// Including zlib module 
const zlib = require("zlib"); 
  
// Declaring input and assigning 
// it a value string 
var input = "Geek"; 
  
// Calling gzip method 
zlib.gzip(input, (err, buffer) => { 
  
  if (!err) { 
  
    console.log(buffer.toString('hex')); 
  }  
  else { 
    console.log(err); 
  } 
}); 
console.log("Data Compressed...");輸出:
Hint:hit control+c anytime to enter REPL. Data Compressed... 1f8b0800000000000003734f4dcd0600619171ab04000000
參考: https://nodejs.org/api/zlib.html#zlib_zlib_gzip_buffer_options_callback
相關用法
- Node.js GM blur()用法及代碼示例
 - Node.js GM drawRectangle()用法及代碼示例
 - Node.js GM sharpen()用法及代碼示例
 - Node.js GM drawPolyline()用法及代碼示例
 - Node.js GM drawEllipse()用法及代碼示例
 - Node.js GM drawCircle()用法及代碼示例
 - Node.js GM drawPolygon()用法及代碼示例
 
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Node.js | zlib.gzip() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
