Natsathorn
Natsathorn

Reputation: 1528

AWS Lambda : module initialization error

I create a Lambda function on AWS with library call mmmagic to check the mimeType from uploaded S3 file event. Everything works fine on my machine with mock test event. I'm sure that I upload all the dependency inside node_modules to Lambda.

This is an error message from Lambda :

module initialization error: Error
at Error (native)
at Object.Module._extensions..node (module.js:597:18)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> 
(/var/task/node_modules/mmmagic/lib/index.js:3:13)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)

Here is my code :

const aws = require('aws-sdk')
const mmagic = require('mmmagic');
const s3 = new aws.S3();

exports.handler = (event, context, callback) => {
    const params = {
        Bucket: event.Records[0].s3.bucket.name,
        Key: event.Records[0].s3.object.key
    }
    s3.getObject(params, (err, data) => {
        if (err) console.log(err, err.stack) // an error occurred
        else {
            var magic = new mmagic.Magic();
            magic.detect(data.Body, function (err, result) {
                if (err) {
                    console.log('Error when try getting mime type:' + err) // logherer
                } else {
                    // do something
                }
            }
        });
    }
})

}

package.json

{
    "aws-sdk": "^2.188.0",
    "mmmagic": "^0.4.6"
}

Upvotes: 0

Views: 3630

Answers (1)

Yevhenii Herasymchuk
Yevhenii Herasymchuk

Reputation: 2137

This problem is related to Node.js version you use and Node.js version that is on Lambda. As you can on their docs the latest version that lambda supports is 6.10

So, the solution for your problem is to

  • downgrade the version of Node.js to 6.10.0. Use, for example nvm
  • remove your node_modules/
  • install all modules with npm i again

And only then try to upload your zip to Lambda.

Upvotes: 2

Related Questions