How to decompress the response? #1155
Replies: 6 comments 11 replies
-
Pipe through a decompressor. |
Beta Was this translation helpful? Give feedback.
-
could you please give an example? |
Beta Was this translation helpful? Give feedback.
-
all my efforts ended with "incorrect header check" |
Beta Was this translation helpful? Give feedback.
-
Does it work with the normal node |
Beta Was this translation helpful? Give feedback.
-
Here is my solution: let data: any;
switch (headers['content-encoding']) {
case 'br':
data = await streamToPromise(body.pipe(createBrotliDecompress()));
break;
case 'gzip':
case 'deflate':
data = await streamToPromise(body.pipe(createUnzip()));
break;
default:
data = await streamToPromise(body);
break;
}
data = /application\/json/.test(headers?.['content-type']) ? JSON.parse(data) : data.toString('utf-8'); |
Beta Was this translation helpful? Give feedback.
-
Using Here is my working solution: import streamToPromise from 'stream-to-promise';
import zlib from 'zlib';
const parseBody = async (response: undici.Dispatcher.ResponseData) => {
const decoders = []
const codings = (response.headers['content-encoding'] || '').split(',').map((x) => x.trim())
for (const coding of codings) {
if (/(x-)?gzip/.test(coding)) {
decoders.push(zlib.createGunzip())
} else if (/(x-)?deflate/.test(coding)) {
decoders.push(zlib.createInflate())
} else if (coding === 'br') {
decoders.push(zlib.createBrotliDecompress())
} else {
decoders.length = 0
break
}
}
return streamToPromise(pipeline(response.body as any, ...decoders, () => { }));
} Example: const response = await undici.request(url);
const parsedBody = await parseBody(response); Hope that helps someone else! |
Beta Was this translation helpful? Give feedback.
-
Just a very simple example, almost exactly as in docs:
The URL http://ad.service.serverside.ai/api/ad-server-static_2.xml actually returns XML, but in the output there is something strange:
���o�0���WxyO�t�
.ik�<>���Mpyx�u�Dn��>���z���,W\kW���K���滴��F,�.-��&ʡUgq&�)дdžl���:>i�
�Y�����b�TUME�sEmC��y�iC���z/��T$Ϻ��_�#E�gX����1���'����p�5�� �HP��r%����7̸G�m���.�UKp͙�W"�/E�\��Һ�@w�Y�0�E�۟�'Y��_ƣ�����gn��mu��O��� ?Z�������gq��i����5s8�? ��&�ݸ�Z�/�2�\���j�+�m�.m���]�7�X8�}9�L]����1]P�ҧ*Z�ء�eW���z�σۻ����]9��:�9�xRa+�˟oe����ځ�` ��pF8#��6'��pF8#�g�3��pF8#�g�3��pF8#�Λ8�3��lg�3��L�;g�3��pF8#�ί�A8#�7r��pF8#���εHd3����l��f�]�K>�b25�ʧ��5��5�"�6R� ��R��%Rqo)2&��˸����i�j9W �o�
��7���-�>
If it is because of gzip compression - how to properly decompress it?
Beta Was this translation helpful? Give feedback.
All reactions