I want to gzip a file hold it in memory and whenever a request comes from the client, i want to output the gzipped data. However I get a error 330 message on my browser (i am using the latest version of chrome)
The code below looks straight forward to me, is there something else I am missing?
var http = require('http');
var url = require('url');
var fs = require('fs');
var zlib = require('zlib');
var gzippedData = '';
//read file into memory
fs.readFile('layout.html', function(err, data){
if(err) throw err;
zlib.gzip(data, function(err, buffer) {
if (err) throw err;
gzippedData = buffer.toString('binary');
});
});
var server = http.createServer(function(req, res){
var path = url.parse(req.url).pathname;
switch (path){
case '/':
res.writeHead(200, {'content-encoding': 'gzip'});
res.write(gzippedData);
res.end();
break;
default:
res.writeHead(404);
res.write('404');
res.end();
}});
server.listen(8080);
Change
to
And you should be good to go!
EDIT: This is because
res.writewill encode the response asutf8by default. You could instead change that tores.write(gzippedData, 'binary'), but that’s unnecessary. It’s cheaper to just keep the reference to the buffer instead of allocating a js string and encoding that yet again.