栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Node.js使用zlib以gzip发送数据

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Node.js使用zlib以gzip发送数据

你在那儿。我可以衷心地同意,该文档还不足以使您了解如何执行此操作。

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);

一个简化就是不使用

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);

…似乎默认情况下会发送UTF-8。但是,当没有默认行为比其他行为更有意义并且我无法立即通过文档进行确认时,我个人宁愿走安全的道路。

同样,如果您需要传递JSON对象,则可以:

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);});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427183.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号