LoginSignup
24
24

More than 5 years have passed since last update.

Node.js で AWSを操作する環境を作る(Mac)

Last updated at Posted at 2015-04-14

Lambdaも出たことだし、node.jsもやってみようということで環境構築します。

1. Nodeのインストール

これみてやる。

$ brew update
$ brew install nodebrew
$ nodebrew install latest (データダウンロードとコンパイルに超時間かかる…)

$ nodebrew list
v0.12.2

current: none


$ nodebrew use v0.12.2

$ echo 'export PATH=$PATH:/Users/ユーザー名/.nodebrew/current/bin' >> ~/.bashrc

nodebrew使うと時間かかるので、サクッと試したいだけなら、 nodebrewではなく、brew installでいいかもしんない。

$ brew install node

2. AWS SDKのインストール

インストールするパッケージの定義作成 (package.json)

cat << EOT > package.json
{
    "dependencies": {
        "aws-sdk": ">= 2.0.9",
        "node-uuid": ">= 1.4.1"
    }
}
EOT

インストール

$ npm install

npm WARN package.json @ No description
npm WARN package.json @ No repository field.
npm WARN package.json @ No README data
node-uuid@1.4.3 node_modules/node-uuid

aws-sdk@2.1.23 node_modules/aws-sdk
├── xmlbuilder@0.4.2
├── xml2js@0.2.8
└── sax@0.5.3

3. サンプルを見てみる

下記にサンプルがあるので見てみる。

$ git clone https://github.com/awslabs/aws-nodejs-sample.git
$ cd aws-nodejs-sample
$ cat sample.js

// Load the SDK and UUID
var AWS = require('aws-sdk');
var uuid = require('node-uuid');

// Create an S3 client
var s3 = new AWS.S3();

// Create a bucket and upload something into it
var bucketName = 'node-sdk-sample-' + uuid.v4();
var keyName = 'hello_world.txt';

s3.createBucket({Bucket: bucketName}, function() {
  var params = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'};
  s3.putObject(params, function(err, data) {
    if (err)
      console.log(err)
    else
      console.log("Successfully uploaded data to " + bucketName + "/" + keyName);
  });
});

S3にバケット作ってファイル上げる例ですね。

実行すると、下記のような感じでUUID付きの長いバケットが作られてその中にhello_world.txt が置かれるようです。

$ node sample.js
Successfully uploaded data to node-sdk-sample-a0038ade-1189-45be-84ca-c19ff5685644/hello_world.txt

確認してみる。

$ aws s3 ls s3://node-sdk-sample-a0038ade-1189-45be-84ca-c19ff5685644/

2015-04-14 20:45:43         12 hello_world.txt

4. APIリファレンスで学ぶ

それぞれのサービス(S3とかDynamoDBとか)の操作方法は下記リファレンスを見てみる。

5. 試しにDynamoDB

$ vim dynamodb.js
var AWS = require('aws-sdk');

var dynamodb = new AWS.DynamoDB({region: 'ap-northeast-1'});

// テーブルリストを取得する

var params = {
    ExclusiveStartTableName: 'STRING_VALUE',
    Limit: 10
};

dynamodb.listTables(params, function(err, data) {
    if (err) {
        console.log(err, err.stack); // an error occurred
    } else {
        console.log(data);           // successful response
    }
});
$ node dynamodb.js

{ LastEvaluatedTableName: 'test9',
  TableNames:
   [ 'test1',
     'test2',
      :
      :
     'test9' ] }

とりあえずテーブル一覧取り出せた。なんとかなりそう。

開発環境構築

ローカルの開発環境として、WebStromを入れて、下記の設定をした。

WebStorm の Node.js 開発環境を構築する

すごくまとまってて良い記事。

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