LoginSignup
5
3

More than 3 years have passed since last update.

aws-sdkを使ってs3にあるjsonデータを取得する方法

Last updated at Posted at 2020-02-26

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を取得しました。

参考文献

この記事は以下の情報を参考にして執筆しました。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3