我有一个运行良好的Lambda nodejs 20.x函数,现在我想从一个名为local_util的模块中导入并使用一个对象,该模块是我编写并放在本地目录中的。然而,Lambda的CloudWatch日志现在显示:
Cannot find module '/var/local_util/index.js' imported from /var/task/index.js
字符串
如何让Lambda找到我的模块?我以前从未尝试过导入自己的nodejs模块。
我创建了一个名为“local_util”的目录,位于lambda代码目录的上一级,将新模块的index.js放在那里。
// local_util/index.js
const lock = {
get: async function (thing) {
// reinvent AWS distributed lock management because it's so fun...
},
release: async function(thing, id) {
// more fun...
}
};
export { lock };
型
然后我运行“npm init”并将这一行添加到新的package.json中:
第一个月
我有这棵树:
lambda/
|__my_lambda_func/
|__index.js
|__package.json
|__package-lock.json
|__node_modules/
|__local_util/
|__index.js
|__package.json
型
我在my_bunda_func/index.js中添加了这一行:import { lock } from '../local_util/index.js';
个
最后,我在my_lambda_func/目录中执行了npm install --install-links ../local_util
,然后执行了zip -qr function.zip .
。当我部署新的function.zip并调用其函数时,我在CloudWatch中得到了Cannot find module '/var/local_util/index.js' imported from /var/task/index.js
错误。
以下是完整的错误:
{
"errorType": "Error",
"errorMessage": "Cannot find module '/var/local_util/index.js' imported from /var/task/index.js",
"code": "ERR_MODULE_NOT_FOUND",
"url": "file:///var/local_util/index.js",
"stack": [
"Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/var/local_util/index.js' imported from /var/task/index.js",
" at new NodeError (node:internal/errors:406:5)",
" at finalizeResolution (node:internal/modules/esm/resolve:238:11)",
" at moduleResolve (node:internal/modules/esm/resolve:850:10)",
" at moduleResolveWithNodePath (node:internal/modules/esm/resolve:972:12)",
" at defaultResolve (node:internal/modules/esm/resolve:1091:79)",
" at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:383:12)",
" at ModuleLoader.resolve (node:internal/modules/esm/loader:352:25)",
" at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:228:38)",
" at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:85:39)",
" at link (node:internal/modules/esm/module_job:84:36)"
]
}
型
1条答案
按热度按时间ilmyapht1#
我的解决方案是将我的import语句从
字符串
到
型
这修复了它,因为相对于我上传的.zip文件的根,
./node_modules/local_util/index.js
实际上是模块文件所在的位置。