0

我有一个 lambda 函数,我从外部 api 获取大约 2.5 MB 大小的缓冲区,但是当我在 JSON 对象中返回相同的缓冲区时,它变得超过 7.5 MB,这大于 lambda 响应大小(6MB)限制,我不确定它是如何发生的。这是我的代码

module.exports.handler = (event, context, callback) => {
  const buffer = getAnswer();
  // This is approx 2.1 MB buffer size
  console.log(`Buffer size ${buffer.byteLength}`);

  const response = {
    headers: {
      'Content-Type': 'application/json',
    },
    isBase64Encoded: false,
    statusCode: 200,
    statusDescription: '200 OK',
    body: JSON.stringify(buffer),
  };
  // Here  size becomes more than 7.5 MB ,I am not sure how it happens
  console.log('This becomes 7.5 MB size', Buffer.byteLength(JSON.stringify(response)), 'bytes');
  context.succeed(response);// Gives error because it exceeds more than 6MB lambda response limit
};
4

1 回答 1

2

检查的结果JSON.stringify(buffer)和原因将是显而易见的。

当您 JSON.stringify 缓冲区时,缓冲区首先转换为这样的对象

{
  "type": "Buffer",
  "data": [byte0, byte1, byte2, byte3, .... ]
}

其中 byteX 是字节的整数值。

如果缓冲区是文本/JSON,则将正文设置为buffer.toString().

如果您需要返回二进制,请考虑将二进制类型添加到 ApiGateway 中的其余 api 并返回数据的 base64 编码版本。

于 2019-04-29T12:58:20.643 回答