问题描述
我要执行以下代码.我尝试过要求mysql和node-mysql,它们都给我相同的错误:
I have the following code that I would like to execute. I have tried requiring mysql and node-mysql and they both give me the same error:
代码:
var AWS = require("aws-sdk");
var mysql = require("mysql");
exports.handler = (event, context, callback) => {
try {
console.log("GOOD");
}
catch (error) {
context.fail(`Exception: ${error}`)
}
};
错误:
{
"errorMessage": "Cannot find module 'mysql'",
"errorType": "Error",
"stackTrace": [
"Function.Module._load (module.js:417:25)",
"Module.require (module.js:497:17)",
"require (internal/module.js:20:19)",
"Object.<anonymous> (/var/task/index.js:2:13)",
"Module._compile (module.js:570:32)",
"Object.Module._extensions..js (module.js:579:10)",
"Module.load (module.js:487:32)",
"tryModuleLoad (module.js:446:12)",
"Function.Module._load (module.js:438:3)"
]
}
如何使用lambda将mysql导入节点或使其工作?
How do I import mysql into node using lambda or get this to work?
推荐答案
好吧,所以预计会发生这种情况.
Ohk so this is expected to happen.
问题在于,AWS Lambda在另一台计算机上运行,并且您无法配置该特定计算机在自定义环境中运行.但是,您可以将mysql
或node-mysql
的节点模块打包为zip并上传到AWS Lambda.步骤是
The problem is that AWS Lambda runs on a different machine and there is no way you can configure that particular machine to run in a custom environment. You can however package the Node Module of mysql
or node-mysql
in a zip and upload to AWS Lambda. Steps are,
-
npm install mysql --save
- 压缩文件夹,并包含您的节点包
- 将此zip文件作为您的代码上传到AWS Lambda中.
npm install mysql --save
- Zip your folder and INCLUDING your node package
- Upload this zip file as your code in AWS Lambda.
您还可以通过使用无服务器框架来采用更好的方法.更多信息此处.使用这种方法,您将编写一个YAML文件,其中包含要用于部署lambda的所有详细信息和配置.在lambda配置下,在package
-> include
部分下指定节点模块(例如nodemodule/**
)的路径.这将打包您所需的代码.稍后使用命令行,您可以部署此lambda.它使用AWS Cloudformation服务,是最受欢迎的资源部署方式之一.
You can also take a better approach by using Serverless Framework. More info here. In this approach, you write a YAML file which contains all the details and configuration you want to deploy your lambda with. Under your lambda configuration, specify path to your node module (say, nodemodule/**
) under package
-> include
section. This will package your required alongwith your code. Later using command line you can deploy this lambda. It uses AWS Cloudformation service and is one of most prefered way of deploying resources.
有关使用无服务器框架打包的更多信息,请参见此处.
More information on packaging using Serverless Framework can be found here.
注意:要使用无服务器框架,需要执行几个步骤,例如为用户获取API密钥,在IAM中设置正确的权限等.这些只是初始设置,以后将不再需要.在使用无服务器框架进行部署之前,请先执行这些操作.
Note: To use serverless framework there couple of steps like getting API keys for your user, setting right permissions in IAM etc. These are just initial setup and won't be need later. Do perform those prior to deploying using serverless framework.
希望这会有所帮助!
这篇关于使用AWS Lambda在NodeJS中找不到MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!