Skip to content

Instantly share code, notes, and snippets.

@eczn
Last active March 15, 2021 07:47
Show Gist options
  • Select an option

  • Save eczn/5f114c1c86ed307c654255ce32a99a34 to your computer and use it in GitHub Desktop.

Select an option

Save eczn/5f114c1c86ed307c654255ce32a99a34 to your computer and use it in GitHub Desktop.
Http Gzipped Chunked Example
import http from 'http';
import zlib from 'zlib';
const wait = (t = 100) => new Promise(r => setTimeout(r, t));
const STR = `<div>${'aaaaaaaaaa'.repeat(500)}</div>`
const server = http.createServer(async (req, res) => {
console.log('ON REQ');
if (req.url !== '/') return res.end();
const zlibStream = zlib.createGzip({
flush: zlib.constants.Z_SYNC_FLUSH,
});
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Transfer-Encoding', 'chunked');
zlibStream.pipe(res);
for (let i = 0; i < 200; i ++) {
// res.write(`aaa`);
zlibStream.write(STR);
await wait(10);
}
zlibStream.end();
// res.end();
});
server.listen(3000);
// test
setTimeout(() => {
console.log('!');
const client = http.request({
host: '0.0.0.0',
protocol: 'http:',
port: '3000'
});
const zlibStream = zlib.createUnzip({
flush: zlib.constants.Z_SYNC_FLUSH,
});
zlibStream.on('data', (e) => {
console.log(e);
})
client.on('response', res => {
res.on('data', (data) => {
zlibStream.write(data);
});
// console.log('res', res);
res.on('end', () => {
zlibStream.end();
console.log('end');
})
})
client.end();
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment