node.js - 如何使用 Google Cloud Function HTTP 响应的 brotli 编码发送

标签 node.js google-cloud-platform google-cloud-functions

如何设置响应内容编码?如果我设置 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/

相关文章:

php - Node.js API 与 express 和 mysql - 仅在设置时应用搜索参数

node.js - 尝试使用聚合将集合复制到另一个集合时出错。

android - 如何使用 Google Play 自定义应用 API 上传 apk

python - 如何从 Google App Engine (python) 启动或停止 Amazon EC2 实例

firebase - 如何通过云功能将 Nuxt SSR 应用部署到 Firebase?

firebase - 如何为 Firebase Cloud Functions 中的特定 header 设置缓存?

javascript - 发送广播数据报

mysql - 如何在 bookshelf.js 中同时插入父表和子表

hadoop - Google Cloud Platform for NiFi 数据路径

python - 云函数将 CSV 发送到云存储