aws-sdk
を使ってs3にあるjsonデータを取得する方法をまとめました。
s3のjson
バケットのtest.json
のデータ「{}
」を取得します。
前提条件
- npmがインストールされていること
- aws側の認証情報設定を行っていること
インストール
$ npm i --save aws-sdk
使い方
ファイルの作成
touch
コマンドでtest.js
ファイルを作成
$ touch test.js
設定
認証情報とapiバージョン、リージョンを設定します。
s3のgetObject
メソッドでファイルデータを取得します。
aws-sdk
では処理をプロミス化するのに.promise()
メソッドが使えます。
test.js
const AWS = require('aws-sdk')
const option = {
credentials: new AWS.Credentials(
'xxxxxxxxxxxxxxx', // AccessKeyIdが入ります
'xxxxxxxxxxxxxxx' // SecretAccessKeyが入ります
),
apiVersions: {
s3: '2006-03-01'
},
region: 'ap-northeast-1'
}
AWS.config.update(option)
const s3 = new AWS.S3()
const param = {
Bucket: 'json',
Key: 'test.json'
};
(async function () {
await s3.getObject(param).promise()
.then(res => console.log(JSON.parse(res.Body.toString())))
.catch(err => console.log(err))
console.log('jsonを取得しました。')
}())
実行
node
コマンドでtest.js
を実行する
$ node test
出力結果
{}
jsonを取得しました。
参考文献
この記事は以下の情報を参考にして執筆しました。