Lambda#
Lambda handler response stream
import util from 'util'import stream from 'stream'const { Readable } = streamconst pipeline = util.promisify(stream.pipeline)export const handler = awslambda.streamifyResponse(async (event, responseStream, _context) => {const requestStream = Readable.from(Buffer.from(new Array(1024 * 1024).join('🚣')))await pipeline(requestStream, responseStream)})
Introduction#
First init a new project
npm init
Install AWS SDK version 3
npm install @aws-sdk/client-s3
Setup type module in the package.json
{"name": "aws-sdk-nodejs-demo","version": "1.0.0","description": "","main": "index.js","type": "module","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "","license": "ISC","dependencies": {"@aws-sdk/client-s3": "^3.344.0"}}
Invoke Lambda#
Install client-lambda in case we want to invoke lambda function by nodejs
npm install @aws-sdk/client-SERVICE
and invoke the lambda function by nodejs
import { InvokeCommand, LambdaClient, LogType } from '@aws-sdk/client-lambda'const client = new LambdaClient({ region: 'us-east-1' })const commnad = new InvokeCommand({FunctionName: 'HelloStream',Payload: JSON.stringify({name: 'haimtran',content: 'Lambda is a compute service that lets you run code without'}),LogType: LogType.Tail})const { Payload, LogResult } = await client.send(commnad)console.log(Payload)// const result = Buffer.from(Payload).toString();// console.log(result)
Lambda Response Stream#
First we can display the receiving stream by curl
curl --request GET https://uuiuhow5ttlcc4enlmo6caqtdq0wfwjw.lambda-url.us-east-1.on.aws/
Second receive by Javascript at client web browser. This is chunk by chunk of byte and decode it to text as the following
'use client'import { useState } from 'react'import { StreamingTextResponse } from 'ai'export default function Home() {const [messages, setMessages] = useState<String[]>([])const callLambda = async () => {const response = await fetch('https://uuiuhow5ttlcc4enlmo6caqtdq0wfwjw.lambda-url.us-east-1.on.aws/',{method: 'GET'})const reader = response.body?.getReader()const read = () => {reader?.read().then(({ done, value }) => {if (done) {console.log('done')return}const decoder = new TextDecoder()console.log(decoder.decode(value))setMessages([...messages, decoder.decode(value)])read()})}read()}return (<main className=""><div className="mx-auto max-w-4xl flex flex-col gap-5"><buttonclassName="rounded-sm px-10 py-3 bg-green-600 text-white"onClick={() => {console.log('call lambda stream')callLambda()}}>Call Lambda</button><div className="w-full break-words bg-slate-200 h-96 overflow-y-auto">{messages.map((message, id) => (<div key={id}>{message}</div>))}</div></div></main>)}
[!IMPORTANT] Please enable CORL and RESPONSE_STREAM MODE in lambda function url