TypeScript で S3 オブジェクトを取得する
TypeScript で AWS SDK for JavaScript v3 を使って S3 からオブジェクトの取得をしてみたところ少し癖があり、単純に string型でオブジェクトの取得ができずハマったので備忘録として残しておきます。
早速サンプルコードを載せてみます。
サンプルコード
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3"; import { Readable } from "stream"; const s3Client = new S3Client({ region: 'ap-northeast-1', endpoint: 'http://s3-ap-northeast-1.amazonaws.com', }); const command = new GetObjectCommand({ Bucket: 'xxx', Key: 'yyy', }); async function main () { try { const res = await s3Client.send(command); const body = res.Body as Readable; let str = ''; for await (const chunk of body) { str += chunk; }; console.log(str); } catch (e) { console.log(e); }; }; (async () => { await main(); })();
ここでハマったのが以下のコードで、Body の型は Readable | ReadableStream | Blob のどれかが返ってきます。
const body = res.Body as Readable;
SDK の サンプルコードには ReadableStream to String と書いている為 ReadableStream が返ってくるのかと思いきや、実際返ってくるのは Readable 型でした。
https://github.com/awsdocs/aws-doc-sdk-examples/blob/5c5d5aa3e729fbebd1c345e774e5745789278ea3/javascriptv3/example_code/s3/src/s3_getobject.js#L33
理解が浅く認識が誤っているかもしれませんが、ReadableStream はブラウザに実装されているインターフェイスで、Node.js では Readable がインターフェイスとして実装されていそうでした。
その為、今回は ReadableStream 型として返すことができなかったのかなと考えています。
とはいえサクッと string として取得できるようにしておいても良いのでは?と思いました。