Skip to content

Instantly share code, notes, and snippets.

@wmakeev
Last active February 15, 2024 05:33
Show Gist options
  • Save wmakeev/c54a8f9503782cf3d9eee0f099940b1b to your computer and use it in GitHub Desktop.
Save wmakeev/c54a8f9503782cf3d9eee0f099940b1b to your computer and use it in GitHub Desktop.
[gzip buffer async] #zip #gzip
import { pipeline } from 'node:stream/promises'
import zlib from 'node:zlib'
/**
* gzip
*
* @param {Buffer | string} data
*/
export async function gzip(data) {
/** @type {Buffer} */
const result = await new Promise((resolve, reject) => {
zlib.gzip(data, (err, res) => {
if (err) reject(err)
else resolve(res)
})
})
return result
}
/**
* ungzip
*
* @param {Buffer | string} data
*/
export async function gunzip(data) {
/** @type {Buffer} */
const result = await new Promise((resolve, reject) => {
zlib.gunzip(data, (err, res) => {
if (err) reject(err)
else resolve(res)
})
})
return result
}
/**
* ungzip stream to buffer
*
* @param {import('stream').Readable} stream
* @returns
*/
export async function gunzipStreamToBuffer(stream) {
/** @type {Buffer[]} */
const chunks = []
await pipeline(stream, zlib.createGunzip(), async function* (src) {
for await (const chunk of src) {
chunks.push(chunk)
}
})
return Buffer.concat(chunks)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment