如何设置响应内容编码?如果我设置 res.header("content-encoding", 'br')
并发送 brotli 版本
exports.helloWorld = (req, res) => {
res.header("content-encoding", 'br')
let message = Buffer.from('Hello World!');
res.write(brotli.compress(message));
res.end();
};
google 函数覆盖 content-encoding
并获取值 content-encoding: gzip
最佳答案
要将 brotli 压缩与 GCP Cloud Functions 结合使用,您必须使用 onRequest 公开快速响应的函数类型,您可以在其中更改响应 header 。
import * as functions from "firebase-functions";
import * as zlib from "zlib";
const runTest = functions
.https.onRequest(async (request, response) => {
// Allowing CORS on my function
response.set('Access-Control-Allow-Origin', "*")
zlib.brotliCompress(JSON.stringify({something: "this is test"}), ((error, result) => {
if(error){
console.error("Error", error)
response.status(500).end()
}
response.set("content-encoding", "br")
response.send(result);
}))
}
export { runTest };
我从使用 gzip 时的 50kB 变为使用 brotli 时的 20kB。
但是,您还必须考虑其他问题。 Brotli 压缩对 CPU 的压缩要求更高。有不同的压缩选项,您可以考虑根据数据的大小更改它们。我还没和他们一起玩呢。我们还可以传输数据吗?使用 Express 框架进行一些调整。
编辑: 这是我的流实现,针对我的用例调整了参数。 我的响应时间值与 gzip 相同,具有相同的 CF 性能,并且传输大小减少了 40%。 (仅供引用:在调整参数之前,我的响应时间非常慢,我认为 BROTLI_MODE_TEXT 有很大帮助!)
import * as stream from "stream";
const stringifiedData = JSON.stringify(inputData);
const inputStream = new stream.Readable(); // Create the stream
inputStream.push(stringifiedData); // Push the data
inputStream.push(null); // End the stream data
const passTrough = new stream.PassThrough()
const brotli = zlib.createBrotliCompress( {
chunkSize: 32 * 1024,
params: {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
[zlib.constants.BROTLI_PARAM_QUALITY]: 4,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: stringifiedData.length
}});
inputStream.pipe(brotli).pipe(passTrough)
passTrough.on('data', (data) => {
response.write(data);
})
passTrough.on('end', () => {
response.end();
})
关于node.js - 如何使用 Google Cloud Function HTTP 响应的 brotli 编码发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57526510/