NodeJS:如何使用 Brotli 将字符串压缩为 Buffer 或 Base64
想使用 Promise?查看这篇关于 Promise 化 brotliCompress 和 brotliDecompress 的文章。
压缩示例
brotli_compress_example.js
const zlib = require('zlib');
// Sample string to compress
const stringToCompress = "This is a sample string to be compressed using Brotli in Node.js";
// Convert the string to a Buffer
const bufferToCompress = Buffer.from(stringToCompress, 'utf-8');
// Compress the buffer using Brotli
zlib.brotliCompress(bufferToCompress, (err, compressedBuffer) => {
if (err) {
console.error('Error compressing the string:', err);
return;
}
console.log('Compressed Buffer:', compressedBuffer);
// Optional: Convert the compressed buffer to a Base64 string for display
const compressedString = compressedBuffer.toString('base64');
console.log('Compressed String (Base64):', compressedString);
});解压示例
brotli_decompress_example.js
// Assume compressedBuffer is the buffer you got from the previous example
zlib.brotliDecompress(compressedBuffer, (err, decompressedBuffer) => {
if (err) {
console.error('Error decompressing the string:', err);
return;
}
const decompressedString = decompressedBuffer.toString('utf-8');
console.log('Decompressed String:', decompressedString);
});Check out similar posts by category:
NodeJS, JavaScript
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow