AWS Lambda failing with run error "ENOENT: no such file or directory, open '/var/task/bridge.js'" - node.js

I have a Node.js 12.x AWS Lambda that is configured in Serverless Framework to fire when a JSON file is dropped into a specific S3 bucket.
Abcg:
handler: Abcg.handle
reservedConcurrency: 1
iamRoleStatements:
- Effect: Allow
Action: lambda:InvokeFunction
Resource: ${cf:LocTransformer-${self:custom.stageEnv}.ABCFnArn}
environment:
GEO_TRANSFORMER_FN: ${self:custom.var.lambdaFn.LocTransformerABC}
EVENT_SOURCE: ${self:custom.var.eventSourceEquipment}
events:
- s3:
bucket: ${self:custom.var.bucket}
existing: true
events:
- s3:ObjectCreated:*
rules:
- prefix: abcg/
- suffix: .json
When a file is dropped, CloudWatch shows the Lambda invocation failing immediately with the following error:
{
"errorType": "Error",
"errorMessage": "ENOENT: no such file or directory, open '/var/task/bridge.js'",
"code": "ENOENT",
"errno": -2,
"syscall": "open",
"path": "/var/task/bridge.js",
"stack": [
"Error: ENOENT: no such file or directory, open '/var/task/bridge.js'",
" at Object.openSync (fs.js:462:3)",
" at Object.readFileSync (fs.js:364:35)",
" at Object.<anonymous> (/var/task/Abcg.js:10201:60)",
" at __webpack_require__ (/var/task/Abcg.js:20:30)",
" at Object.<anonymous> (/var/task/Abcg.js:59145:5)",
" at __webpack_require__ (/var/task/Abcg.js:20:30)",
" at Object.<anonymous> (/var/task/Aabcg.js:59127:18)",
" at __webpack_require__ (/var/task/Aabcg.js:20:30)",
" at Object.<anonymous> (/var/task/Aabcg.js:44894:15)",
" at __webpack_require__ (/var/task/Abcg.js:20:30)"
]
}
I believe it's failing even before entering my Lambda code because I have some early log statements and these aren't appearing in CloudWatch. And, the project doesn't use Webpack, so I assume this reference in the stack trace is coming from a dependency.
Has anyone seen this error before, in particular the reference to /var/task/bridge.js, which I can't see in my project?

Related

HandlerNotFound at trigger aws lambda function

I have a problem with deployed to AWS Lambda function. I create an trigger to SQS queue, when I have new message then my trigger (index.receiver) processing this message. So, here is my code:
index.ts
import receiver from "./sqs/receiver";
exports.receiver = receiver;
sqs/receiver.ts
const receiver: SQSHandler = async (event) => {
//some logic
};
export default receiver;
After trigger this function, I see in AWS CloudWatch that nothing is working correctly and throw me this error:
{
"errorType": "Runtime.HandlerNotFound",
"errorMessage": "index.receiver is undefined or not exported",
"stack": [
"Runtime.HandlerNotFound: index.receiver is undefined or not exported",
" at Object.module.exports.load (/var/runtime/UserFunction.js:144:11)",
" at Object.<anonymous> (/var/runtime/index.js:43:30)",
" at Module._compile (internal/modules/cjs/loader.js:999:30)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)",
" at Module.load (internal/modules/cjs/loader.js:863:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:708:14)",
" at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)",
" at internal/main/run_main_module.js:17:47"
]
}
Here is also my project tree:
.serverless
node_modules
sqs
- receiver.ts
index.ts
package.json
serverless.yml
and serverless.yml
service: some-name
provider:
name: aws
runtime: nodejs12.x
region: eu-central-1
apiGateway:
minimumCompressionSize: 1024 # Enable gzip compression for responses > 1 KB
environment:
AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1
# SQS Permission given
iamManagedPolicies:
- 'arn:aws:iam::aws:policy/AmazonSQSFullAccess'
functions:
receiver:
handler: index.receiver
events:
- sqs: <my-sqs-arn>
Can someone tell me what I'm doing wrong? Thanks for any help!
I resolve this problem. Problem was in this, that in my serverless.yml I point handler like this: handler: index.receiver but, when we use Typescript we should point it to dist/index.receiver because AWS can handle only JS files, we also need to remember about build project with this function before using serverless deploy.

AWS Lambda function error: Cannot find module 'lambda'

I am trying to deploy a REST API in AWS using serverless. Node version 14.17.5.
My directory structure:
When I deploy the above successfully I get the following error while trying to access the api.
2021-09-28T18:32:27.576Z undefined ERROR Uncaught Exception {
"errorType": "Error",
"errorMessage": "Must use import to load ES Module: /var/task/lambda.js\nrequire() of ES modules is not supported.\nrequire() of /var/task/lambda.js from /var/runtime/UserFunction.js is an ES module file as it is a .js file whose nearest parent package.json contains \"type\": \"module\" which defines all .js files in that package scope as ES modules.\nInstead rename lambda.js to end in .cjs, change the requiring code to use import(), or remove \"type\": \"module\" from /var/task/package.json.\n",
"code": "ERR_REQUIRE_ESM",
"stack": [
"Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /var/task/lambda.js",
"require() of ES modules is not supported.",
"require() of /var/task/lambda.js from /var/runtime/UserFunction.js is an ES module file as it is a .js file whose nearest parent package.json contains \"type\": \"module\" which defines all .js files in that package scope as ES modules.",
"Instead rename lambda.js to end in .cjs, change the requiring code to use import(), or remove \"type\": \"module\" from /var/task/package.json.",
"",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13)",
" at Module.load (internal/modules/cjs/loader.js:937:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:778:12)",
" at Module.require (internal/modules/cjs/loader.js:961:19)",
" at require (internal/modules/cjs/helpers.js:92:18)",
" at _tryRequire (/var/runtime/UserFunction.js:75:12)",
" at _loadUserApp (/var/runtime/UserFunction.js:95:12)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:43:30)",
" at Module._compile (internal/modules/cjs/loader.js:1072:14)"
]
}
As per the suggestion in the error I tried changing the lambda.js to lambda.cjs. Now I get the following error
2021-09-28T17:32:36.970Z undefined ERROR Uncaught Exception {
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'lambda'\nRequire stack:\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
"stack": [
"Runtime.ImportModuleError: Error: Cannot find module 'lambda'",
"Require stack:",
"- /var/runtime/UserFunction.js",
"- /var/runtime/index.js",
" at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:43:30)",
" at Module._compile (internal/modules/cjs/loader.js:1072:14)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)",
" at Module.load (internal/modules/cjs/loader.js:937:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:778:12)",
" at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)",
" at internal/main/run_main_module.js:17:47"
]
}
serverless.yml
service: APINAME #Name of your App
useDotenv: true
configValidationMode: error
provider:
name: aws
runtime: nodejs14.x # Node JS version
memorySize: 512
timeout: 15
stage: dev
region: us-east-1 # AWS region
lambdaHashingVersion: 20201221
functions:
api:
handler: lambda.handler
events:
- http: ANY /{proxy+}
- http: ANY /
lambda.js
import awsServerlessExpress from 'aws-serverless-express'
import app from './index.js'
const server = awsServerlessExpress.createServer(app)
export const handler = (event, context) => {
awsServerlessExpress.proxy(server, event, context)
}
aws-cli commands
docker run --rm -it amazon/aws-cli --version
docker run --rm -it amazon/aws-cli configure
docker run --rm -it amazon/aws-cli serverless deploy
serverless commands:
docker run --rm -it amazon/aws-cli serverless deploy
serverless config credentials --provider aws --key <KEY> --secret <SECRET>
node ./node_modules/serverless/bin/serverless config credentials --provider aws --key <KEY> --secret <SECRET>
After reading up a couple of answers I have tried the following:
Made sure package.json includes "type": "module"
Deleted node_modules and package-lock.json and reinstalled all of them (since the version of node was updated during development)
What am I doing wrong?
Converted all imports to require() and all exports to module.exports
Removed "type": "module" from package.json
Everything works like a charm. It is not a solution to the question asked but making things work became more important.
Instead rename lambda.js to end in .cjs, change the requiring code to use
import(),
and remove
"type": "module"
from /var/task/package.json. It is there in the error.

Why Cannot find module 'request-promise' ? ( Runtime.ImportModuleError)

I create a simple NodeJS project and want to upload it as an aws lambda, but I get this error when I hit Test:
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'request-promise'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
"trace": [
"Runtime.ImportModuleError: Error: Cannot find module 'request-promise'",
"Require stack:",
"- /var/task/index.js",
"- /var/runtime/UserFunction.js",
"- /var/runtime/index.js",
" at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:43:30)",
" at Module._compile (internal/modules/cjs/loader.js:1085:14)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)",
" at Module.load (internal/modules/cjs/loader.js:950:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:790:14)",
" at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)",
" at internal/main/run_main_module.js:17:47"
]
}
I import every think, but the lambda can't find modules that already exist in node_modules.
the structure of my project is like this:
project_name>
node_modules
index.js
package.json
package-lock.json
index.js
let request = require("request-promise");
exports.handler = async () => {
// my functions
...
}
Do you have any idea how to solve this issue please!
I solved the issue by installing request
npm install request --save
then I deployed the project and it seems every thing is ok.

Runtime.ImportModuleError - Error: Cannot find module 'tslib'

error message
undefined ERROR Uncaught Exception {"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'tslib'"}
folder structure
src
handler.ts -> fn.getAll
template.yaml
GetAll:
Type: AWS::Serverless::Function
Properties:
Handler: handler.getAll
CodeUri: dist/out-tsc
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref master
Environment:
Variables:
USE_EVENT_BRIDGE: !Ref UseEventBridge
Events:
Api1:
Type: Api
Properties:
Path: /getAll
Method: get
Output folder:
dist/out-tsc
handler.js -> fn.getAll
After typescript compile using tsc. output files are generated at targeted location. In each JS handler file i have tslib require statement. Below error message denotes the same. When I click on the tslib it refers to the node modules perfectly. How can I overcome this?
I have updated the tsconfig.json with below options in compileroptions. Installed tslib in node modules
"paths": {
"tslib": ["node_modules/tslib/tslib.d.ts"]
}
Error:
START RequestId: 820d8905-61f3-4045-9704-3cc7bd4901df Version: $LATEST
2021-02-12T11:18:32.904Z
undefined ERROR Uncaught Exception {"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'tslib'","stack":["Runtime.ImportModuleError: Error: Cannot find module 'tslib'","
at _loadUserApp (/var/runtime/UserFunction.js:100:13)","
at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","
at Object.<anonymous> (/var/runtime/index.js:45:30)","
at Module._compile (internal/modules/cjs/loader.js:778:30)","
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)","
at Module.load (internal/modules/cjs/loader.js:653:32)","
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)","
at Function.Module._load (internal/modules/cjs/loader.js:585:3)","
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)","
at startup (internal/bootstrap/node.js:283:19)"]}

Runtime.ImportModuleError Error: Cannot find module 'axios/lib/utils' Serverless

I am using the Serverless framework. Backend as node.js. I have several microservices and all others are working fine, but now I have created now microservice where I have not used Axios but still, it is throwing error in the console.
One more issue is that in my local system it works perfectly, but as I push the same into the server then it starts creating issues.
This is the sample code which is throwing error
const { IamAuthenticator } = require('ibm-watson/auth');
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
async function textAnalyse(req, res) {
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2019-07-12',
authenticator: new IamAuthenticator({
apikey: 'API KEY'
}),
url: 'https://URL/natural-language-understanding/api'
});
const analyzeParams = {
'text': HtmlToText.fromString('Test text here'),
'features': {
'entities': {
'sentiment': true,
'limit': 100
}
}
};
const analysis = await naturalLanguageUnderstanding.analyze(analyzeParams);
// prepare the response object
res.send({ analysis: analysis });
}
Error in AWS Cloud watch
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'axios/lib/utils'",
"stack": [
"Runtime.ImportModuleError: Error: Cannot find module 'axios/lib/utils'",
" at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:45:30)",
" at Module._compile (internal/modules/cjs/loader.js:778:30)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)",
" at Module.load (internal/modules/cjs/loader.js:653:32)",
" at tryModuleLoad (internal/modules/cjs/loader.js:593:12)",
" at Function.Module._load (internal/modules/cjs/loader.js:585:3)",
" at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)",
" at startup (internal/bootstrap/node.js:283:19)",
" at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)"
]
}
I found the fixes for this.
when we call third-party API from our Lambda it requires the Axios to be implemented internally. So you need to create a folder that will have a package.json file with the dependency
"dependencies": {
"axios": "^0.19.2"
}
Then add the layer in the functions from AWS UI, left side menu
Then add the layer to your function
Now, by doing the above activity the issue will be resolved and Axios dependency is added successfully individually to the microservice.
Also, what you name the folders matters before zipping. Review these AWS docs for folder naming so you can import the library like you would in any other project.
https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

Resources