Last active
February 15, 2024 05:33
-
-
Save wmakeev/c54a8f9503782cf3d9eee0f099940b1b to your computer and use it in GitHub Desktop.
[gzip buffer async] #zip #gzip
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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