The zlib module in Node.js provides a set of compression and decompression utilities for handling data in various formats. It’s built on the zlib library, which is widely used for data compression, and allows developers to efficiently compress and decompress data streams, making it essential for optimizing storage and network transmission. This module is available in the Azion Runtime through Node.js compatibility, so functions can use it to compress response payloads with Gzip or decompress incoming data closer to your users, reducing bandwidth usage.
The example below shows how to use the zlib module in a function:
/** * An example of using Node.js Zlib API in an Azion Function. * Support: * - Partially supported (Extended by library `browserify-zlib`) * @module runtime-apis/nodejs/zlib/main * @example * // Execute with Azion Bundler: * npx edge-functions build * */import zlib from "node:zlib";
/** * An example of using the Node.js Zlib API in an Azion Function. * @param {*} event * @returns {Promise<Response>} */const main = async (event) => { const body = event.body ?? "Hello, World!"; const output = zlib.gzipSync(body);
// decode const decom = zlib.gunzipSync(Buffer.from(output)).toString(); console.log(decom);
return new Response(output.toString("base64"), { headers: { "Content-Type": "application/octet-stream", "Content-Encoding": "gzip", }, });};
export default main;