Salman
Salman

Reputation: 9447

Node.JS deflate/gzip response text

I saw the example shown here

response.writeHead(200, { 'content-encoding': 'deflate' });
raw.pipe(zlib.createDeflate()).pipe(response);

I tried to send the response by creating a read stream and sending deflated output.

But I am looking for a way to do it without read stream, because the text I have comes from another HTTP request. I simply used to response.write(text);

I tried a couple of things including

zlib.deflate(text, function (err, buffer) {
    if (err) throw err;
    response.write(buffer);
    response.end();
});

But the browser says invalid or unsupported form of compression.

What am I doing wrong?

connect's code says

return stream
    ? stream.write(new Buffer(chunk, encoding))
    : write.call(res, chunk, encoding);

So is it like only streams will be processed?

Upvotes: 2

Views: 5131

Answers (2)

Salman
Salman

Reputation: 9447

So, I managed to solve the problem. Here is the code

var zlib = require('zlib');
var connect = require('connect');
var fs = require('fs');

var server = connect()
    // .use(connect.compress()) It didn't work either
    .use(function (req, res, next) {
        var text = fs.readFileSync('test.js');

        zlib.deflate(text, function (err, buffer) {
            if (err) throw err;

            res.writeHead(200, {
                'Content-Encoding': 'deflate',
                'Content-Type': 'text/javascript'
            });

            res.end(buffer);
        });
    })
    .listen(1337);

I don't know what mistake I did earlier causing it not to work. I am not sure if any version conflict was causing the problem or something else. but finally, the above code works for me ;)

Upvotes: 0

robertklep
robertklep

Reputation: 203304

Are you using Express? If so, just use the compress middleware:

app.use(express.compress());

http://expressjs.com/api.html#compress

Upvotes: 1

Related Questions