zlib.deflate()方法是Zlib模塊的內置應用程序編程接口,用於壓縮大量數據。
用法:
zlib.deflate( buffer, options, callback )
參數:此方法接受上述和以下所述的三個參數:
- buffer:它可以是Buffer,TypedArray,DataView,ArrayBuffer和字符串的類型。
- options:它是一個可選參數,其中包含zlib選項。
- callback:它包含回調函數。
返回值:壓縮後返回數據塊。
以下示例說明了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
相關用法
- Node.js GM modulate()用法及代碼示例
- Node.js GM monochrome()用法及代碼示例
- Node.js GM equalize()用法及代碼示例
- Node.js GM enhance()用法及代碼示例
- Node.js GM threshold()用法及代碼示例
- Node.js GM thumbnail()用法及代碼示例
- Node.js GM whitePoint()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Node.js | zlib.deflate() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。