Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs send data in gzip using zlib

Tags:

node.js

gzip

I tried to send the text in gzip, but I don't know how. In the examples the code uses fs, but I don't want to send a text file, just a string.

const zlib = require('zlib');
const http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});

    const text = "Hello World!";
    res.end(text);

}).listen(80);
like image 358
friction Avatar asked Feb 08 '13 17:02

friction


People also ask

Does gzip use zlib?

zlib was adapted from the gzip code. All of the mentioned patents have since expired. The zlib library supports Deflate compression and decompression, and three kinds of wrapping around the deflate streams.

Can zlib decompress gzip?

The zlib module can be used to implement support for the gzip , deflate and br content-encoding mechanisms defined by HTTP. The HTTP Accept-Encoding header is used within an http request to identify the compression encodings accepted by the client.


1 Answers

You're half way there. I can heartily agree that the documentation isn't quite up to snuff on how to do this;

const zlib = require('zlib');
const http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});

    const text = "Hello World!";
    const buf = new Buffer(text, 'utf-8');   // Choose encoding for the string.
    zlib.gzip(buf, function (_, result) {  // The callback will give you the 
        res.end(result);                     // result, so just send it.
    });
}).listen(80);

A simplification would be not to use the Buffer;

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});

    const text = "Hello World!";
    zlib.gzip(text, function (_, result) {  // The callback will give you the 
      res.end(result);                     // result, so just send it.
    });
}).listen(80);

...and it seems to send UTF-8 by default. However, I personally prefer to walk on the safe side when there is no default behavior that makes more sense than others and I can't immediately confirm it with documentation.

Similarly, in case you need to pass a JSON object instead:

const data = {'hello':'swateek!'}

res.writeHead(200, {'Content-Type': 'application/json', 'Content-Encoding': 'gzip'});
const buf = new Buffer(JSON.stringify(data), 'utf-8');
zlib.gzip(buf, function (_, result) {
    res.end(result);
});
like image 61
Joachim Isaksson Avatar answered Sep 24 '22 22:09

Joachim Isaksson