LoginSignup
6
1

More than 5 years have passed since last update.

ローカルで AWS Lambda をうごかしてみる。そのための exports 入門サンプル。

Last updated at Posted at 2017-01-21

AWS Lambda を使いはじめました。マネジメントコンソール画面から Test ボタンを押せば Lambda を走らせることができるのですが、それだと毎回、マネジメントコンソールのソースをいじらないといけません。できれば、ローカルのファイルを修正して、ローカルでその Lambda を走らせたいです。

きっと、いろいろ方法はあると思いますが、とても安易に、node index.js 的なノリで軽く動かしたいと思います。

exports.hoge について

~/workspace/hoge.js
exports.piyo = function(){
    console.log("Hello");
}
~/workspace
$ node
> const hoge = require('./hoge.js')
undefined
> hoge.piyo()
Hello
undefined

このようにできます。

Lambda の index.js で試してみる。

Lambda の index.js は以下の構造になっていますので、

index.js
exports.handler = (event, context, callback) => {
    ...処理...
}

hoge.js と同じノリで叩いてみます。

$ node
> const lambda = require('./index.js')
undefined
> lambda.handler()
TypeError: callback is not a function
    at Object.exports.handler.https.get.req.on [as handler] (/Users/mochizuki/Developments/ferretone-pardot/index.js:45:3)
    at repl:1:8
    at REPLServer.defaultEval (repl.js:262:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:431:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:211:10)
    at REPLServer.Interface._line (readline.js:550:8)

こんな感じになります。

コールバックが function じゃないぞ、と言われていますので、適当に引数をセットしてみます。

> lambda.handler(null, null, function(){})
undefined
> STATUS: 200

無事できました。

ひとまず、これで僕のニーズは満たされたので、すこしはデバッグがやりやすくなりました。

まだまだ、知らないことがたくさんなので、すこしずつできることを増やして行きたいです。 :walking_tone1:

追記 require キャッシュ強い問題

index.js を更新したあとに、lambda.handler() を叩いてもキャッシュされてるので更新されません。結局以下のフィアルを用意して、node lambda_test.js を叩いて動かすことにしました。

lambda_test.js
var lambda = require('./index.js')
lambda.handler(null, null, function(){})
delete require.cache[require.resolve('./index.js')]
$ node lambda_test.js
6
1
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
6
1