如何从AWS Lambda Layer导入一个JSON对象?

huangapple go评论66阅读模式
英文:

How to import a JSON object from an AWS Lambda Layer?

问题

这似乎很简单,但我一直在尝试弄清楚它。我似乎找不到网上的解决方案。

//nodejs/models.js:
// City = ...
// ...
module.exports = {City, Country, Coupon, Player, Pollfish, Tree};

在压缩了nodejs后,我将zip文件上传为AWS Layer,并将该Layer添加到我的Lambda函数中。

当我尝试在Lambda函数中检索对象时:

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const {Player} = require('./models.js');

它导致了一个错误:

2023-01-06T09:19:49.469Z undefined ERROR 未捕获的异常 {"errorType":"Runtime.ImportModuleError","errorMessage":"错误:找不到模块 'models.js'\nRequire stack:\n- /var/task/index.mjs","stack":["Runtime.ImportModuleError: 错误:找不到模块 'models.js'","Require stack:","- /var/task/index.mjs"," at _loadUserApp (file:///var/runtime/index.mjs:1000:17)"," at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1035:21)"," at async start (file:///var/runtime/index.mjs:1200:23)"," at async file:///var/runtime/index.mjs:1206:1"]}

那么正确的方法应该是什么呢?

英文:

This may seem simple but I have had a hard time trying to figure it out. I could not seem to find the solution on the web too.

//nodejs/models.js:
// City = ...
// ...
module.exports = {City, Country, Coupon, Player, Pollfish, Tree};

After zipping nodejs, I uploaded the zip file as an AWS Layer and added the layer to my Lambda function.

When I tried to retrieve the objects in my Lambda function:

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const {Player} = require('./models.js');

It resulted in an error:

2023-01-06T09:19:49.469Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'models.js'\nRequire stack:\n- /var/task/index.mjs","stack":["Runtime.ImportModuleError: Error: Cannot find module 'models.js'","Require stack:","- /var/task/index.mjs","    at _loadUserApp (file:///var/runtime/index.mjs:1000:17)","    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1035:21)","    at async start (file:///var/runtime/index.mjs:1200:23)","    at async file:///var/runtime/index.mjs:1206:1"]}

So what should be the proper way to do it?

答案1

得分: 1

我明白了!应该是:

const {Player} = require('/opt/nodejs/models.js');
英文:

I got it! It should be:

const {Player} = require('/opt/nodejs/models.js');

huangapple
  • 本文由 发表于 2023年1月6日 17:30:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75029121.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定