Open2
AWS JavaScript SDK v3 サンプルコード
S3 listObject
import { S3 } from '@aws-sdk/client-s3'
//以下のリソースがあることを確認する
//arn:aws:s3:::sample-log/a/b/c/d.log
it('list s3 object', async () => {
const s3 = new S3({
region: 'ap-northeast-1',
})
const prefix =
'a/b/c/'
const response = await s3.listObjectsV2({
Bucket: 'sample-log',
Prefix: prefix,
})
if (!response.Contents) {
throw new Error('failed')
}
expect(response.Contents.length).toBe(1)
expect(response.Contents[0].Key).toBe(
prefix + 'd.log'
)
})
S3 getObject
import { S3 } from '@aws-sdk/client-s3'
import { Readable } from 'stream'
// Apparently the stream parameter should be of type Readable|ReadableStream|Blob
// The latter 2 don't seem to exist anywhere.
//https://github.com/aws/aws-sdk-js-v3/issues/1877#issuecomment-755430937
async function streamToString(stream: Readable): Promise<string> {
return await new Promise((resolve, reject) => {
const chunks: Uint8Array[] = []
stream.on('data', (chunk) => chunks.push(chunk))
stream.on('error', reject)
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')))
})
}
export const getObjectContent: (bucket: string, key: string) => Promise<{ contents: string }> =
async (bucket: string, key: string) => {
let contents = ''
const s3 = new S3({})
const response = await s3.getObject({
Bucket: bucket,
Key: key,
})
contents = await streamToString(response.Body as Readable)
return {
contents: contents,
}
}