Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

lambda-local

ashiina743kMIT2.2.0TypeScript support: included

Commandline tool and API to run Lambda functions on your local machine.

lambda, amazon, aws, AWS, local, run

readme

Lambda-local

NPM

Lambda-local unit tests

Lambda-local lets you test NodeJS Amazon Lambda functions on your local machine, by providing a simplistic API and command-line tool.

It does not aim to be perfectly feature proof as projects like serverless-offline or docker-lambda, but rather to remain very light (it still provides a fully built Context, handles all of its parameters and functions, and everything is customizable easily).

The main target are unit tests and running lambda functions locally.

Install

npm install -g lambda-local

Build

make build

Or

npm install
npm install --only=dev
npm run build

Usage

  • As an API: You can also use Lambda local directly in a script. For instance, it is interesting in a MochaJS test suite in order to get test coverage.
  • As a command line tool: You can use Lambda-local as a command line tool.

If you're unsure about some definitions, see Definitions for terminology.

About: API

LambdaLocal

API accessible with:

const lambdaLocal = require("lambda-local");

Or on TypeScript (supported on 1.7.0+):

import lambdaLocal = require("lambda-local");

lambdaLocal.execute(options)

Executes a lambda given the options object, which is a dictionary where the keys may be:

Key name Description
event requested event as a json object
lambdaPath requested path to the lambda function
lambdaFunc pass the lambda function. You cannot use it at the same time as lambdaPath
profilePath optional, path to your AWS credentials file
profileName optional, aws profile name. Must be used with
lambdaHandler optional handler name, default to handler
region optional, AWS region, default to us-east-1
timeoutMs optional, timeout, default to 3000 ms
esm boolean, marks that the script is an ECMAScript module (use import), default false
environment optional, extra environment variables for the lambda
envfile optional, load an environment file before booting
envdestroy optional, destroy added environment on closing, default to false
verboseLevel optional, default 3. Level 2 dismiss handler() text, level 1 dismiss lambda-local text and level 0 dismiss also the result. Level -1 only displays handler() text.
callback optional, lambda third parameter callback. When left out a Promise is returned
onInvocationEnd optional. called once the invocation ended. useful when awslambda.streamifyResponse is used to distinguish between end of response stream and end of invocation.
clientContext optional, used to populated clientContext property of lambda second parameter (context)
contextOverwrite optional, a function that overwrites the context object. It can get and overwrite the values of the context (such as awsRequestId).

lambdaLocal.setLogger(logger)

lambdaLocal.getLogger()

Those functions allow to access the winston logger used by lambda-local.

API examples

A lot of examples, especially used among Mocha, may be found in the test files over: here

Basic usage: Using Promises
const lambdaLocal = require('lambda-local');

var jsonPayload = {
    'key': 1,
    'another_key': "Some text"
}

lambdaLocal.execute({
    event: jsonPayload,
    lambdaPath: path.join(__dirname, 'path_to_index.js'),
    profilePath: '~/.aws/credentials',
    profileName: 'default',
    timeoutMs: 3000
}).then(function(done) {
    console.log(done);
}).catch(function(err) {
    console.log(err);
});

Basic usage: using callbacks

const lambdaLocal = require('lambda-local');

var jsonPayload = {
    'key': 1,
    'another_key': "Some text"
}

lambdaLocal.execute({
    event: jsonPayload,
    lambdaPath: path.join(__dirname, 'path_to_index.js'),
    profilePath: '~/.aws/credentials',
    profileName: 'default',
    timeoutMs: 3000,
    callback: function(err, data) {
        if (err) {
            console.log(err);
        } else {
            console.log(data);
        }
    },
    clientContext: JSON.stringify({clientId: 'xxxx'})
});

About: CLI

Available Arguments

  • -l, --lambda-path <lambda index path> (required) Specify Lambda function file name.
  • -e, --event-path <event path> (required --watch is not in use) Specify event data file name.
  • -h, --handler <handler name> (optional) Lambda function handler name. Default is "handler".
  • -t, --timeout <timeout> (optional) Seconds until lambda function timeout. Default is 3 seconds.
  • --esm (optional) Load lambda function as ECMAScript module.
  • -r, --region <aws region> (optional) Sets the AWS region, defaults to us-east-1.
  • -P, --profile-path <aws profile name> (optional) Read the specified AWS credentials file.
  • -p, --profile <aws profile name> (optional) Use with -P: Read the AWS profile of the file.
  • -E, --environment <JSON {key:value}> (optional) Set extra environment variables for the lambda
  • --wait-empty-event-loop (optional) Sets callbackWaitsForEmptyEventLoop=True => will wait for an empty loop before returning. This is false by default because our implementation isn't perfect and only "emulates" it.
  • --envdestroy (optional) Destroy added environment on closing. Defaults to false
  • -v, --verboselevel <3/2/1/0> (optional) Default 3. Level 2 dismiss handler() text, level 1 dismiss lambda-local text and level 0 dismiss also the result.
  • --envfile <path/to/env/file> (optional) Set extra environment variables from an env file
  • --inspect [[host:]port] (optional) Starts lambda-local using the NodeJS inspector (available in nodejs > 8.0.0)
  • -W, --watch [port] (optional) Starts lambda-local in watch mode listening to the specified port [1-65535].

CLI examples

# Simple usage
lambda-local -l index.js -h handler -e examples/s3-put.js

# Input environment variables
lambda-local -l index.js -h handler -e examples/s3-put.js -E '{"key":"value","key2":"value2"}'

Running lambda functions as a HTTP Server (Amazon API Gateway payload format version 2.0.)

A simple way you can run lambda functions locally, without the need to create any special template files (like Serverless plugin and SAM requires), just adding the parameter --watch. It will raise a http server listening to the specified port (default is 8008). You can then call the lambda as mentionned here: https://docs.aws.amazon.com/lambda/latest/dg/urls-invocation.html

lambda-local -l examples/handler_gateway2.js -h handler --watch 8008

curl --request POST \
  --url http://localhost:8008/ \
  --header 'content-type: application/json' \
  --data '{
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
}'
{"message":"This is a response"}

You can also use the following format for your event, in order to avoid using the Amazon API Gateway format:

{
    "event": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    }
}

In this case, the event will be passed directly to the handler.

About: Definitions

Event data

Event sample data are placed in examples folder - feel free to use the files in here, or create your own event data. Event data are just JSON objects exported:

// Sample event data
module.exports = {
    foo: "bar"
};

Context

The context object has been sampled from what's visible when running an actual Lambda function on AWS, and the available documentation They may change the internals of this object, and Lambda-local does not guarantee that this will always be up-to-date with the actual context object.

AWS-SDK

As of version 2.0.0, lambda-local no longer packages AWS-SDK in its dependencies. To run a function that makes use of this module, make sure to install it as a dependency in your project.

Development

  • Run make to install npm modules. (Required to develop & test lambda-local)
  • Run make test to execute the mocha test.
    • Run make clean to reset the repository.

License

This library is released under the MIT license.

changelog

ChangeLog

2.1.2 (2023/08/19)

  • Fix regression: support for NodeJS>=8
  • Fix regression: old events in --watch

2.1.1 (2023/07/22)

  • Bug fix: ESM path on Windows
  • Downgrade commander-js

2.1.0 (2023/07/20)

  • Support API gateway in --watch
  • Support ECMAScript (thanks tdanecker #230)
  • Support Lambda streaming (thanks Skn0tt #229)
  • Update dependencies

2.0.3 (2022/09/12)

  • Fix callbackWaitsForEmptyEventLoop on recent NodeJS versions (>=16) (#217)
  • Support clientContext as an object (#223)
  • Remove useless warning (#224)
  • Update dependencies

2.0.2 (2022/03/08)

  • correctly mirror lambda's behaviour when synchronously returning (thanks Snk0tt)
  • Update dependencies

2.0.1 (2021/12/22)

  • Fix memoryLimitInMB being wrongly parsed as int
  • Update dependencies

2.0.0 (2021/06/19)

  • BREAKING CHANGE: removed aws-sdk dependency. This allows to make lambda-local significantly smaller
  • Drop Node 8 & Bump depencies
  • Minor CLI fixes
  • Move CI from Travis to Github

1.7.4 (2020/10/12)

  • Fix crash when an Error is raised with no stack (#GH202)
  • Add --version and lambdaLocal.version support
  • Improve logging of the --watch option
  • Bump dependencies & minor build improvements

1.7.3 (2020/06/04)

  • Bump dependencies. No API changes

1.7.2 (2020/04/13)

  • Add --watch parameter
  • Bump dependencies

1.7.1 (2020/01/28)

  • Add support for _HANDLER
  • Update environment variables computation & consistency with context

1.7.0 (2020/01/17)

  • Migrate to TypeScript (#191)

1.6.3 (2019/07/04)

  • Security updates (update dependencies that had vulnerabilities: mocha).
  • Pick up AWS profile from env AWS_PROFILE or AWS_DEFAULT_PROFILE (thanks to @illusori)

1.6.2 (2019/04/30)

  • Documentation changes. No API changes

1.6.1 (2019/04/15)

  • Update for Winston 3
  • Refactor console output manager

1.5.3 (2019/04/15)

  • Better handling of TimeoutError: now passed to context as other exceptions
  • Improved Makefile (thanks to @joechrysler)
  • Drop NodeJS < 6, therefore update all dependencies

1.5.2 (2018/12/02)

  • New: ability to specify the context manualy (thanks to Nathan Wright)
  • New: Implement proper callbackWaitsForEmptyLoop
  • Fix ARN context environment vars (thanks to @bar-sc)
  • Better outputs management (circular outputs)

1.5.1 (2018/06/08)

  • NodeJS >= 10 proper detection
  • Timeout message fix (thanks to @ribizli)

1.5.0 (2018/06/06)

  • Make context an object
  • Support multi-threading & nested calls
  • Context is regenerated on each run (e.g. awsRequestId will change)

1.4.8 (2018/05/26)

  • Read default AWS config files
  • Improve absolute/relative path finding
  • Handle syntax error in handlers

1.4.7 (2018/04/03)

  • Support async functions (thanks to @hoegertn)

1.4.6 (2018/03/08)

  • Fix region detection
  • Add --envdestroy option to restore the environment after testing.
  • Support builtin Error object handling
  • More examples & better README

1.4.5 (2017/11/15)

  • Better environment variables managing
  • Fix lambda ending rules (context.done/fail/succeed)

1.4.4 (2017/10/24)

  • Timeout fix
  • Better context management
  • Add execution time log

1.4.3 (2017/09/23)

  • Several token fixes
  • New log system, using a verbose level
  • Bug fixes

1.4.2 (2017/03/09)

  • Added promise support
  • Better JSON parse error handling for environment variables

1.4.1 (2017/02/09)

  • Fixed critical bug

1.4.0 (2017/02/08)

  • Added support for environment variables

1.3.0 (2016/11/26)

  • Fixed critical bug (logger)

1.2.0 (2016/11/23)

  • Added mock functionality
  • Dropped Node.js v0.1, v0.12 suport

1.1.0 (2016/9/15)

  • The default behavior of lambda-local now does not forcefully call the callback function (-c option).
  • Added AWS region option -r. Defaults to us-east-1.
  • Added AWS profile name option -p.

1.0.0 (2016/6/10)

  • lambda-local can now be imported as a node module, and be executed from other node.js programs

0.0.10 (2016/5/29)

  • Support for Node.js 4.3.2 runtime
  • Added feature to import AWS profile from commandline option
  • Added necessary environment variables

0.0.9 (2016/4/9)

  • Fixed package.json information for npm

0.0.8 (2016/4/9)

0.0.7 (2016/2/21)

  • Minor bug fix: Now correctly outputs the error object when Context.done() has an error.

0.0.6 (2015/11/13)

  • Added support for fail and succeed methods

0.0.5 (2015/1/21)

  • First release