103

Node.js Alexa Task Issue

I'm currently coding a Node.js Alexa Task via AWS Lambda, and I have been trying to code a function that receives information from the OpenWeather API and parses it into a variable called weather. The relevant code is as follows:

var request = require('request');
var weather = "";
function isBadWeather(location) {
      var endpoint = "http://api.openweathermap.org/data/2.5/weather?q=" + location + "&APPID=205283d9c9211b776d3580d5de5d6338";
      var body = "";
      request(endpoint, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                  body = JSON.parse(body);
                  weather = body.weather[0].id;
            }
      });
}

function testWeather()
{
      setTimeout(function() {
      if (weather >= 200 && weather < 800)
            weather = true;
      else
            weather = false;
      console.log(weather);
      generateResponse(buildSpeechletResponse(weather, true), {});
      }, 500);
}

I ran this snippet countless times in Cloud9 and other IDEs, and it seems to be working flawlessly. However, when I zip it into a package and upload it to AWS Lambda, I get the following error:

{
    "errorMessage": "Cannot find module '/var/task/index'",
    "errorType": "Error",
    "stackTrace": [
        "Function.Module._load (module.js:276:25)",
        "Module.require (module.js:353:17)",
        "require (internal/module.js:12:17)"
    ]
}

I installed module-js, request, and many other Node modules that should make this code run, but nothing seems to fix this issue. Here is my directory, just in case:

- planyr.zip
   - index.js
   - node_modules
   - package.json

Does anyone know what the issue could be?

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
Anthony Krivonos
  • 4,596
  • 4
  • 16
  • 31
  • Here is the log output for my code: `START RequestId: 46c71292-debf-11e6-a013-1be2c415a9c1 Version: $LATEST Unable to import module 'index': Error at Function.Module._resolveFilename (module.js:325:15) at Function.Module._load (module.js:276:25) at Module.require (module.js:353:17) at require (internal/module.js:12:17) END RequestId: 46c71292-debf-11e6-a013-1be2c415a9c1 REPORT RequestId: 46c71292-debf-11e6-a013-1be2c415a9c1 Duration: 55.76 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 16 MB ` – Anthony Krivonos Jan 20 '17 at 03:28
  • 3
    In addition to the answer on zipping using terminal on a Mac, also make sure your codefile is called 'index.js'. Mine had a more descriptive name, generating the error. – Art Apr 29 '17 at 04:27
  • 1
    @Art This was my issue. I zipped up a test.js and it threw an unhandled error. After changing it to index.js it worked fine. Thanks. – Hudspeth Dec 18 '18 at 15:31

9 Answers9

246

Fixed it! My issue was that I tried to zip the file using my Mac's built-in compression function in Finder.

If you're a Mac user, like me, you should run the following script in terminal when you are in the root directory of your project (folder containing your index.js, node_modules, etc. files).

zip -r ../yourfilename.zip *

For Windows:

Compress-Archive -LiteralPath node_modules, index.js -DestinationPath yourfilename.zip
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Anthony Krivonos
  • 4,596
  • 4
  • 16
  • 31
  • 9
    i was zipping like so: "zip -r folder folder.zip" and of course this failed. thanks for the tip to just zip the files and not the directory – Dane Macaulay Mar 20 '17 at 22:52
  • 6
    How about windows? – Alok Rajasukumaran Jul 27 '17 at 08:17
  • also make sure to name the function `index.js` – DrDirk Aug 02 '17 at 09:19
  • Is there any way to do this from outside the directory? – andrhamm Aug 07 '17 at 19:02
  • 1
    @andrhamm Yes. The format is `zip -r /path/to/destination.zip /path/to/source/directory/*`. That zips the contents of the directory. If you want to zip the directory itself too, use /path/to/source/directory without the *. – Qaz Aug 08 '17 at 23:43
  • in windows git bast throwing error "command not found", how to resolve this any idea ? – Pardeep Jain Nov 18 '17 at 11:06
  • If you have an issue with your node modules after uploading the zip you created using the zip command here, check to see that [this](https://stackoverflow.com/a/54426847/2320598) issue didn't happen to you. Looks like `Compress-Archive` can cause the node modules to be uploaded as a flat tree. Also if you have a number of dev dependencies, be sure to delete your node modules folder first and use the `npm install --production` to save space! – kbuechl Apr 30 '19 at 21:41
  • This is exactly what I do before uploading my lambda zip file. – Ankur Kothari Jan 02 '23 at 14:02
26

Check that file name and handler name are same:

In this case we expect that all our code will be in <code>bundle.ls</code> file

That means that zip file has bundle.js file that exports handler function:

exports.handler = (event, context, callback) => {//...}
Zoe
  • 27,060
  • 21
  • 118
  • 148
zooblin
  • 2,172
  • 2
  • 27
  • 33
25

Update to the accepted answer: When this error occurs, it means your zip file is not in the valid form which AWS requires.

If you double click on zip you will find your folder inside that your code file,but lambda wants that when you double click on zip it shoud show direct code files.

To achieve this:

open terminal  
cd your-lambda-folder 
zip -r index.zip *

Then, upload index.zip to AWS Lambda.

entpnerd
  • 10,049
  • 8
  • 47
  • 68
Ashutosh Jha
  • 15,451
  • 11
  • 52
  • 85
8

In my case it was because I had the handler file in inner src directory.

I had to change the 'Handler' property within Lambda from:

index.handler

to

src/index.handler
Pete
  • 1,500
  • 2
  • 16
  • 33
  • I also ran in to this; [Windows] it was simply that I was right clicking on the `API` part of my repo and using `Send To > Compressed Folder`. This creates a zip with structure `api/etc`, hence the exception! – C Bauer Mar 20 '19 at 22:06
3

This is probably a permissions issue with files inside your deployment zip. Try chmod 777 your files before packaging them in a zip file.

spg
  • 9,309
  • 4
  • 36
  • 41
  • 2
    Unfortunately, that doesn't seem to fix the issue. I tried compressing the `planyr` folder within another folder to no avail. My handler name and main JavaScript file names match (`index`). – Anthony Krivonos Jan 20 '17 at 02:36
  • `chmod 777` is a bad advice... this is opening permissions to public to write, read and execute. Please always find the route cause of the issue. Always try to understand the security implications of executing whatsoever someone in the internet tell you to do. Security is important and must be in our code by default. – Exadra37 Feb 14 '19 at 12:12
3

In my case the archive contained a folder "src" with index.js file, so I had to put to the handler: "src/index.handler"

enter image description here

Sergey S
  • 889
  • 12
  • 18
2

In my case I had to replace

exports.handler = function eventHandler (event, context) {

with

exports.handler = function (event, context, callback) {
ianaz
  • 2,490
  • 3
  • 28
  • 37
0

I got this error when I was using lambci/lambda:nodejs8.10 in windows.

I'd tried all of the solution listed above but none of which could help me deal with my issue(even though the error stack look the same as the question).

Here is my simple solution:

  1. using --entrypoint flag to run a container to find out if the file is mounted into the container. It turns out I may got the share drive issue with my Docker Desktop.
  2. I switched my docker daemon that day before, but everything works fine except this problem.
  3. Anyway, remount my drive to Docker Desktop, you can both use the docker command or just open the Docker Desktop setting to apply.
Diya Li
  • 1,048
  • 9
  • 21
0

In my case this was caused by Node running out of memory. I fixed that by adding --memory-size 1500 to my aws lambda create-function ... command.

Samuli Pahaoja
  • 2,660
  • 3
  • 24
  • 32