乐闻世界logo
搜索文章和话题

How to load npm modules in AWS Lambda?

1个答案

1
  1. Initialize the Project in Your Local Development Environment: Create a new project directory locally and run the npm init command to initialize a Node.js project. This will generate a package.json file.

  2. Install Required npm Modules: Use the npm install command to install all necessary npm modules for your project. For example, to use axios for HTTP requests, run npm install axios, which will add it to your package.json file.

  3. Write the Lambda Function Code: Create a file (e.g., index.js) in your project and write your Lambda function code. In this code, use the require statement to import the installed npm modules. For example:

javascript
const axios = require('axios'); exports.handler = async (event) => { const response = await axios.get('https://api.example.com/data'); return { statusCode: 200, body: JSON.stringify(response.data), }; };
  1. Package Your Lambda Function: Package your code files and the node_modules directory into a ZIP archive. Ensure the root of the ZIP file contains your code files and the node_modules folder.

  2. Upload to AWS Lambda: In the AWS Lambda console, create a new Lambda function or update an existing one. Upload the ZIP file to the function's code section. AWS Lambda will automatically extract the file and make the npm modules available during function execution.

  3. Deploy and Test: Deploy your Lambda function and test it to verify that it correctly utilizes the npm modules.

Example Scenario:

Suppose you need to access a REST API and retrieve data within a Lambda function. You decide to use the axios module to simplify HTTP request handling. Follow the steps above to install axios, write the Lambda function to fetch API data, and package the project for upload to AWS Lambda. This allows your Lambda function to leverage axios for network requests and data processing.

2024年8月2日 14:32 回复

你的答案