What is lambda-local?
The lambda-local npm package allows you to run and test AWS Lambda functions locally. This can be useful for development and debugging purposes, as it enables you to simulate the AWS Lambda environment on your local machine.
What are lambda-local's main functionalities?
Run Lambda Function Locally
This feature allows you to execute a Lambda function locally by specifying the event, the path to the Lambda function, AWS credentials, and a timeout. The code sample demonstrates how to set up and run a Lambda function locally using lambda-local.
const lambdaLocal = require('lambda-local');
const path = require('path');
lambdaLocal.execute({
event: require('./event.json'),
lambdaPath: path.join(__dirname, 'index.js'),
profilePath: '~/.aws/credentials',
profileName: 'default',
timeoutMs: 3000
}).then(function(done) {
console.log(done);
}).catch(function(err) {
console.log(err);
});
Simulate AWS Context
This feature allows you to simulate the AWS context object that is passed to Lambda functions. The code sample shows how to define a custom context and use it when executing a Lambda function locally.
const lambdaLocal = require('lambda-local');
const path = require('path');
const context = {
functionName: 'myLambdaFunction',
awsRequestId: '1234567890',
logGroupName: '/aws/lambda/myLambdaFunction',
logStreamName: '2021/01/01/[$LATEST]abcdef1234567890'
};
lambdaLocal.execute({
event: require('./event.json'),
lambdaPath: path.join(__dirname, 'index.js'),
context: context,
timeoutMs: 3000
}).then(function(done) {
console.log(done);
}).catch(function(err) {
console.log(err);
});
Custom Environment Variables
This feature allows you to set custom environment variables for your Lambda function. The code sample demonstrates how to set an environment variable and use it when running a Lambda function locally.
const lambdaLocal = require('lambda-local');
const path = require('path');
process.env.MY_ENV_VAR = 'myValue';
lambdaLocal.execute({
event: require('./event.json'),
lambdaPath: path.join(__dirname, 'index.js'),
timeoutMs: 3000
}).then(function(done) {
console.log(done);
}).catch(function(err) {
console.log(err);
});
Other packages similar to lambda-local
serverless-offline
The serverless-offline package allows you to run Serverless applications and AWS Lambda functions locally. It integrates with the Serverless Framework and provides a more comprehensive local development environment, including support for API Gateway, DynamoDB, and other AWS services. Compared to lambda-local, serverless-offline offers a broader range of features and better integration with the Serverless Framework.
localstack
LocalStack is a fully functional local AWS cloud stack that allows you to develop and test cloud applications offline. It supports a wide range of AWS services, including Lambda, S3, DynamoDB, and more. Compared to lambda-local, LocalStack offers a more comprehensive local AWS environment, making it suitable for testing complex applications that rely on multiple AWS services.
Lambda-local
Lambda-local lets you test Amazon Lambda functions on your local machine with sample event data.
The context
of the Lambda function is already loaded so you do not have to worry about it.
You can pass any event
JSON object as you please.
Install
npm install -g lambda-local
Usage
As a command line tool
You can use Lambda-local as a command line tool.
lambda-local -l index.js -h handler -e examples/s3-put.js
lambda-local -l index.js -h handler -e examples/s3-put.js -E '{"key":"value","key2":"value2"}'
In another node.js script
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.
See API for more infos
About: CLI
Command
- -l, --lambda-path (required) Specify Lambda function file name.
- -e, --event-path (required) Specify event data file name.
- -h, --handler (optional) Lambda function handler name. Default is "handler".
- -t, --timeout (optional) Seconds until lambda function timeout. Default is 3 seconds.
- -n, --no-force-callback (optional) Force the function to stop after having called the handler function even if context.done/succeed/fail was not called.
- -r, --region (optional) Sets the AWS region, defaults to us-east-1.
- -P, --profile-path (optional) Read the specified AWS credentials file.
- -p, --profile (optional) Use with -P: Read the AWS profile of the file.
- -E, --environment <JSON {key:value}> (optional) Set extra environment variables for the lambda
- --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
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:
module.exports = {
foo: "bar"
};
Context
The context
object has been directly extracted from the source visible when running an actual Lambda function on AWS.
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
Since the Amazon Lambda can load the AWS-SDK npm without installation, Lambda-local has also packaged AWS-SDK in its dependencies.
If you want to use this, please use the "-p" option with the aws credentials file. More infos here:
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-config-files
About: API
LambdaLocal
execute(options)
Executes a lambda given the options
object where keys are:
event
- requested event as a json objectlambdaPath
- requested path to the lambda functionlambdaFunc
- pass the lambda function. You cannot use it at the same time as lambdaPathprofilePath
- optional, path to your AWS credentials fileprofileName
- optional, aws profile name. Must be used withlambdaHandler
- optional handler name, default to handler
region
- optional, AWS region, default to us-east-1
callbackWaitsForEmptyEventLoop
- optional, default to true
. Setting it to false
will call the callback when your code do, before finishing lambda-localtimeoutMs
- optional, timeout, default to 3000 msenvironment
- optional, extra environment variables for the lambdaenvfile
- optional, load an environment file before bootingenvdestroy
- optional, destroy added environment on closing, default to falseverboseLevel
- optional, default 3. Level 2 dismiss handler() text, level 1 dismiss lambda-local text and level 0 dismiss also the result.callback
- optional, lambda third parameter callback. When left out a Promise is returned
setLogger(logger)
If you are using winston, this pass a winston logger instead of the console.
Example Usage for API
Basic: In another node.js script
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);
}
}
});
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);
});
Use lambda-local to Mock
You can use Lambda local to mock your lambda then run it, using MochaJS and SinonJS
In this sample, we assume that you got a test function like this:
exports.getData = function getData(){
return "WrongData";
}
exports.handler = function(event, context) {
context.done(null, exports.getData());
};
Then you will be able to use in your test.js mocha file, something like:
var jsonPayload = {
}
var done, err;
before(function (cb) {
var lambdalocal = require('lambda-local');
lambdalocal.setLogger(your_winston_logger);
var lambdaFunc = require("path_to_test-function.js");
sinon.mock(lambdaFunc).expects("getData").returns("MockedData");
lambdalocal.execute({
event: jsonPayload,
lambdaFunc: lambdaFunc,
lambdaHandler: "handler",
callbackWaitsForEmptyEventLoop: true,
timeoutMs: 3000,
callback: function (_err, _done) {
err = _err;
done = _done;
cb();
},
verboseLevel: 1
});
});
describe("Your first test", function () {
it("should return mocked value", function () {
assert.equal(done, "MockedData");
});
});
... Other tests
Development
- Run
make
to install npm modules. (Required to develop & test lambda-local) - Run
make test
to execute the mocha test.
License
This library is released under the MIT license.