Sei a metà strada. Sono pienamente d'accordo sul fatto che la documentazione non è del tutto priva di snuff su come farlo;
var zlib = require('zlib');
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});
var text = "Hello World!";
var 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);
Una semplificazione non sarebbe utilizzare il Buffer
;
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html', 'Content-Encoding': 'gzip'});
var text = "Hello World!";
zlib.gzip(text, function (_, result) { // The callback will give you the
res.end(result); // result, so just send it.
});
}).listen(80);
... e sembra inviare UTF-8 per impostazione predefinita. Tuttavia, personalmente preferisco camminare sul lato sicuro quando non esiste un comportamento predefinito che abbia più senso di altri e non posso confermarlo immediatamente con la documentazione.
Allo stesso modo, in caso di necessità di passare un oggetto JSON invece:
var data = {'hello':'swateek!'}
res.writeHead(200, {'Content-Type': 'application/json', 'Content-Encoding': 'gzip'});
var buf = new Buffer(JSON.stringify(data), 'utf-8');
zlib.gzip(buf, function (_, result) {
res.end(result);
});
fonte
2013-02-08 18:00:35
Che cosa significa il valore di '_' rappresentare nel richiamata? Sto pensando forse a un errore, ma non riesco a trovarlo documentato ... – cprcrack
@cprcrack E 'solo un parametro non utilizzato per il callback. '_' è valido come nome di parametro/variabile e io lo uso come marcatore che rende abbastanza ovvio (per me) che non è usato. –
Mi viene l'idea, ma vorrei comunque sapere perché il chiamante di callback sta usando quel parametro e se a volte può essere usato/utile. – cprcrack