How to test AWS Lambda handler locally using NodeJS?

kroe761 picture kroe761 · Aug 25, 2018 · Viewed 21.4k times · Source

I am following these instructions to create a basic web scraper that executes in Lambda. I have experience writing selenium code, but not with Node JS. I got the project running in Lambda, but when I tried editing the project locally in order to execute the selenium code I want, It doesn't work. Anything in the exports.handler doesn't get executed when I run node index.js. How would I execute this project locally? Thanks!

Answer

jmk picture jmk · Oct 22, 2018

This is what I did:

index.js

exports.handler = async (event) => {
    console.log('hello world');

    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!')
    };

    return response;
};

package.json

"scripts": {
  "locally": "node -e \"console.log(require('./index').handler({}));\""
}

Shell

npm run locally

Output

> node -e "console.log(require('./index').handler({}));"

hello world
Promise { { statusCode: 200, body: '"Hello from Lambda!"' } }