LoginSignup
10
7

More than 5 years have passed since last update.

ローカルでS3的なもの(s3rver)を動かしてaws-cliで操作する

Posted at

S3を使うプログラムをローカルでテストしたくなったので、s3rverというものを使ってみました。

インストール

$ yarn add --dev s3rver 
yarn add v0.27.5
 :
Done in 70.65s.

npm install --dev s3rverでも大丈夫です。

確認

global installではないので、node_modules/.bin/s3rverで起動します。

$ node_modules/.bin/s3rver --help

  Usage: s3rver [options]


  Options:

    --version                   output the version number
    -h, --hostname [value]      Set the host name or ip for the server
    -p, --port <n>              Set the port of the http server
    -s, --silent                Suppress log messages
    -i, --indexDocument [path]  Index Document for Static Web Hosting
    -e, --errorDocument [path]  Custom Error Document for Static Web Hosting
    -d, --directory [path]      Data directory
    -c, --cors                  Enable CORS
    -h, --help                  output usage information

格納先ディレクトリを準備して起動

$ mkdir -p ./temp/s3rver
$ node_modules/.bin/s3rver -d ./temp/s3rver
now listening on host localhost and port 4568

デフォルトでは4568ポートでListenしています。

aws-cliで操作する

aws-cliのs3コマンドまたはs3apiコマンドに--endpoint http://localhost:4568を指定すると利用できます。

Bucketの作成と表示(s3api使用)

$ aws --endpoint http://localhost:4568 s3api create-bucket --bucket test-bucket
{
    "Location": "/test-bucket"
}

$ aws --endpoint http://localhost:4568 s3api list-buckets
{
    "Buckets": [
        {
            "Name": "test-bucket",
            "CreationDate": "2017-09-23T06:13:07.000Z"
        }
    ],
    "Owner": {
        "DisplayName": "S3rver",
        "ID": "123"
    }
}

ファイルの操作(s3使用)

$ aws --endpoint http://localhost:4568 s3 cp ./README.md s3://test-bucket/
upload: ./README.md to s3://test-bucket/README.md

$ aws --endpoint http://localhost:4568 s3 ls s3://test-bucket/
2017-09-23 15:14:49       7052 README.md

javascript sdk (nodejs)から利用

AWS.config.update()でendpointを指定することで利用できます。

const AWS = require('aws-sdk');
AWS.config.update({ endpoint: 'http://localhost:4568' });
const s3 = new AWS.S3();

s3.listBuckets().promise()
  .then((data) => console.log(data.Buckets));

$ node index.js 
[ { Name: 'test-bucket', CreationDate: 2017-09-23T06:14:49.000Z } ]

これとaws-sam-localを組み合わせれば、Lambdaの開発もかなり捗りそうです。

(参考)実体は?

s3rver -d <directory>のディレクトリにファイルの実体があるのですが、そのまま置かれているわけではないようです。

$ tree -a ./temp/s3rver/test-bucket/
./temp/s3rver/test-bucket/
└── README.md
    ├── .dummys3_content
    └── .dummys3_metadata

ファイル名(S3上のKey)がディレクトリ構成で表現され、.dummys3_contentが実体、.dummys3_metadataにcreationDateなどが格納されていました。

この構造を理解していると、テストデータとしてS3にObjectを置くことができそうですが、s3 syncs3 cpが使えるので、そちらのほうが楽だと思います。

10
7
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
10
7