Error: Cannot find module 'node-fetch'\nRequire stack:\n- /var/task IN AWS Lambda - node.js

I am not getting any error in local with node-fetch in the package.json also have node-fetch dependencies but when I deployed in aws lambda then this dependencies not found.
import fetch from 'node-fetch';
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'node-fetch'\nRequire stack:\n- /var/task/query1.js\n- /var/task/query1Main.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
"trace": [
"Runtime.ImportModuleError: Error: Cannot find module 'node-fetch'",
"Require stack:",
"- /var/task/query1.js",
"- /var/task/query1Main.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: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"
]
}

You have to declare external packages as layers for a lambda
https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

I had the same issue using Node version 18.x and fixed after downgrading to 16.x
This can be done in the lambda page -> scroll down to Runtime settings
I hope you already resolved the issue but I'm posting this in case someone else finds it useful.

Related

Why does datadog lambda instrumentation return a `datadog-lambda-js/handler.handler is undefined or not exported`?

The Datadog AWS Lambda instrumentation seems unreliable to me. Every few invocations, I get the following error:
"errorType": "Runtime.HandlerNotFound",
"errorMessage": "/opt/nodejs/node_modules/datadog-lambda-js/handler.handler is undefined or not exported",
"stack": [
"Runtime.HandlerNotFound: /opt/nodejs/node_modules/datadog-lambda-js/handler.handler is undefined or not exported",
" at HandlerNotFound.ExtendedError [as constructor] (/opt/nodejs/node_modules/datadog-lambda-js/runtime/errors.js:113:28)",
" at new HandlerNotFound (/opt/nodejs/node_modules/datadog-lambda-js/runtime/errors.js:131:42)",
" at load (/opt/nodejs/node_modules/datadog-lambda-js/runtime/user-function.js:151:15)",
" at Object.<anonymous> (/opt/nodejs/node_modules/datadog-lambda-js/handler.js:65:59)",
" 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 Module.require (internal/modules/cjs/loader.js:887:19)",
" at require (internal/modules/cjs/helpers.js:74:18)"
]
}
To start the instrumentation, I run the following code.
datadog-ci lambda instrument \
-f my-lambda-name \
-r my-region \
-v 50 -e 15 \
--service my-service \
--env my-env \
--version 1.0
Any idea what I'm doing wrong?
Depending on the runtime environment, you should point to a different version of the datadog layer extensions.
Python, for example, uses -v 50 -e 15, but Node.js handlers should use a different version, -v 66 -e 16.
All of this is available in the documentation: https://docs.datadoghq.com/serverless/installation/nodejs/?tab=datadogcli

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 '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

AWS Lambda Node.js 6.10 : "errorMessage": "Cannot find module 'cfn-response'",

I am trying to deploy a lambda function in Nodejs 6.10 and I am getting this error:
Response:
{
"errorMessage": "Cannot find module 'cfn-response'",
"errorType": "Error",
"stackTrace": [
"Module.require (module.js:497:17)",
"require (internal/module.js:20:19)",
"Object. (/var/task/index.js:2:20)",
"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)"
]
}
Function Logs:
START RequestId: d1123bc9-1722-11e8-84a2-c9cba9c66de8 Version: $LATEST
Unable to import module 'index': Error
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/task/index.js:2:20)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
END RequestId: d1123bc9-1722-11e8-84a2-c9cba9c66de8
REPORT RequestId: d1123bc9-1722-11e8-84a2-c9cba9c66de8 Duration: 87.34 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 32 MB
I am using Node.js 6.10 version for this method and did inline code edit.
Code I am trying to execute:
var response = require('cfn-response');
exports.handler = function(event, context) {
var input = parseInt(event.ResourceProperties.Input);
var responseData = {Value: input * 5};
response.send(event, context, response.SUCCESS, responseData);
};
Any clues?
Mostly it is because of the way zipping the files making the problem. Instead of zipping the root folder you have to select all files and zip it like below,
Please upload all files and subfolders like below. Please include node_modules folder as well in the zip.

Resources