Skip to content

Instantly share code, notes, and snippets.

@thiskevinwang
Created May 17, 2023 13:09
Show Gist options
  • Save thiskevinwang/dd0afffd3a50e9f37ca3dcb5854b3417 to your computer and use it in GitHub Desktop.
Save thiskevinwang/dd0afffd3a50e9f37ca3dcb5854b3417 to your computer and use it in GitHub Desktop.
lambda-node-code-that-streams
import util from "util";
import stream from "stream";
const { Readable } = stream;
const pipeline = util.promisify(stream.pipeline);
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
export const handler = awslambda.streamifyResponse(
async (event, responseStream, context) => {
const s3 = new S3Client({ region: "us-east-1" });
const input = {
Bucket: "-------------------FIXME------------------",
Key: "-------------FIXME--------------",
};
const command = new GetObjectCommand(input);
// console.log("sending...");
const item = await s3.send(command);
// console.log(item.Body);
console.log(Object.getOwnPropertyNames(item.Body));
// [
// "_readableState",
// "_events",
// "_eventsCount",
// "_maxListeners",
// "socket",
// "httpVersionMajor",
// "httpVersionMinor",
// "httpVersion",
// "complete",
// "rawHeaders",
// "rawTrailers",
// "aborted",
// "upgrade",
// "url",
// "method",
// "statusCode",
// "statusMessage",
// "client",
// "_consuming",
// "_dumped",
// "req",
// "transformToByteArray",
// "transformToString",
// "transformToWebStream",
// ];
const requestStream = item.Body.transformToWebStream();
// item.Body is a Readable stream
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/getobjectcommandoutput.html#body
// https://stackoverflow.com/questions/67366381/aws-s3-v3-javascript-sdk-stream-file-from-bucket-getobjectcommand
const metadata = {
statusCode: 200,
headers: {
"Content-Type": "image/jpeg",
"X-Custom-Header": "Example-Custom-Header",
},
};
responseStream = awslambda.HttpResponseStream.from(
responseStream,
metadata
);
// const requestStream = Readable.from(
// Buffer.from(new Array(1024 * 1024).join("🚣"))
// );
await pipeline(requestStream, responseStream);
}
);
@thiskevinwang
Copy link
Author

awslambda is a special global var available on AWS Node Lambdas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment