📜  Node.js zlib.deflate() 方法

📅  最后修改于: 2022-05-13 01:56:45.650000             🧑  作者: Mango

Node.js zlib.deflate() 方法

zlib.deflate() 方法是 Zlib 模块的内置应用程序编程接口,用于压缩数据块。

句法:

zlib.deflate( buffer, options, callback )

参数:此方法接受三个参数,如上所述,如下所述:

  • buffer:可以是 Buffer、TypedArray、DataView、ArrayBuffer 和字符串类型。
  • options:它是一个可选参数,包含 zlib 选项。
  • 回调:它保存回调函数。

返回值:返回压缩后的数据块。

下面的例子说明了在 Node.js 中zlib.deflate() 方法的使用:

示例 1:

// Node.js program to demonstrate the     
// deflate() method
  
// Including zlib module
const zlib = require("zlib");
  
// Declaring input and assigning
// it a value string
var input = "Geeks";
  
// Calling deflate method
zlib.deflate(input, (err, buffer) => {
  
  if (!err) {
  
    console.log(buffer.toString('base64'));
  } 
  else {
    console.log(err);
  }
});
console.log("Data Compressed...");

输出:

Data Compressed...
eJxzT03NLgYABXQB8A==

示例 2:

// Node.js program to demonstrate the     
// deflate() method
  
// Including zlib module
const zlib = require("zlib");
  
// Declaring input and assigning
// it a value string
var input = "Geeks";
  
// Calling deflate method
zlib.deflate(input, (err, buffer) => {
  
  if (!err) {
  
    console.log(buffer.toString('bas64'));
  } 
  else {
    console.log(err);
  }
});
console.log("Data Compressed...");

输出:

Data Compressed...
buffer.js:631
  throw new ERR_UNKNOWN_ENCODING(encoding);
  ^

TypeError [ERR_UNKNOWN_ENCODING]: Unknown encoding: bas64
    at stringSlice (buffer.js:631:9)    
    at Buffer.toString (buffer.js:667:10)    
    at Deflate.zlib.deflate [as cb] 
(/home/runner/BeautifulMiserlySourcecode/index.js:17:24)
    at Deflate.zlibBufferOnEnd (zlib.js:133:10)
    at Deflate.emit (events.js:203:15)
    at Deflate.EventEmitter.emit (domain.js:448:20)
    at endReadableNT (_stream_readable.js:1143:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

在这里,编码数据时发生错误,因此会引发错误。

参考: https://nodejs.org/api/zlib.html#zlib_zlib_deflate_buffer_options_callback