

# 编写支持响应流式处理的 Lambda 函数
<a name="config-rs-write-functions"></a>

为响应流式处理函数编写处理程序不同于典型的处理程序模式。编写流式处理函数时，请确保执行以下操作：
+ 使用 `awslambda.streamifyResponse()` 装饰器包装您的函数。`awslambda` 全局对象由 Lambda 的 Node.js 运行时环境提供。
+ 正常结束流，以确保所有数据处理完成。

## 配置处理程序函数以流式处理响应
<a name="config-rs-write-functions-handler"></a>

要向运行时系统指示 Lambda 应该流式处理函数的响应，您必须使用 `streamifyResponse()` 装饰器包装函数。从而指示运行时系统使用正确的响应流式处理逻辑路径，同时确保函数能够流式处理响应。

`streamifyResponse()` 装饰器接受可接受以下参数的函数：
+ `event` – 提供有关函数 URL 的调用事件的信息，例如 HTTP 方法、查询参数和请求正文。
+ `responseStream` – 提供可写流。
+ `context` – 提供的方法和属性包含有关调用、函数和执行环境的信息。

`responseStream` 对象为 [Node.js `writableStream`](https://nodesource.com/blog/understanding-streams-in-nodejs/)。与任何此类流一样，您应该使用 `pipeline()` 方法。

**注意**  
`awslambda` 全局对象由 Lambda 的 Node.js 运行时自动提供，无需导入。

**Example 支持响应流式处理的处理程序**  

```
import { pipeline } from 'node:stream/promises';
import { Readable } from 'node:stream';

export const echo = awslambda.streamifyResponse(async (event, responseStream, _context) => {
  // As an example, convert event to a readable stream.
  const requestStream = Readable.from(Buffer.from(JSON.stringify(event)));

  await pipeline(requestStream, responseStream);
});
```

尽管 `responseStream` 提供了写入流的 `write()` 方法，但建议您尽可能使用 [https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-callback](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-callback)。使用 `pipeline()` 能够确保可写流不会被速度更快的可读流所淹没。

## 结束流
<a name="config-rs-write-functions-end"></a>

确保在处理程序返回之前正确结束流。`pipeline()` 方法会自动处理此问题。

对于其他使用案例，请调用 `responseStream.end()` 方法以正确结束流。此方法表示不应向流写入更多数据。如果您使用 `pipeline()` 或 `pipe()` 写入流，则不需要使用此方法。

从 Node.js 24 开始，在您的处理程序返回或响应流结束后，Lambda 不再等待未解决的 Promise 完成。如果您的函数依赖于其他异步操作，例如计时器或获取，则应在处理程序中 `await` 它们。

**Example 使用 pipeline() 结束流的示例**  

```
import { pipeline } from 'node:stream/promises';

export const handler = awslambda.streamifyResponse(async (event, responseStream, _context) => {
  await pipeline(requestStream, responseStream);
});
```

**Example 不使用 pipeline() 结束流的示例**  

```
export const handler = awslambda.streamifyResponse(async (event, responseStream, _context) => {
  responseStream.write("Hello ");
  responseStream.write("world ");
  responseStream.write("from ");
  responseStream.write("Lambda!");
  responseStream.end();
});
```