How to call module.exports from handler in AWS Lambda (Node.js)

AWS Lambda expects your module to export an object that contains a handler function. In your Lambda configuration you then declare the file that contains the module, and the name of the handler function.

The way modules are exported in Node.js is via the module.exports property. The return value of a require call is the contents of the module.exports property at the end of the file evaluation.

exports is just a local variable pointing to module.exports. You should avoid using exports, and instead use module.exports, since some other piece of code may overwrite module.exports, leading to unexpected behaviour.

In your first code example, the module correctly exports an object with a single function handler. In the second code example, however, your code exports a single function. Since this does not match AWS Lambda's API, this does not work.

Consider the following two files, export_object.js and export_function.js:

// export_object.js

function internal_foo () {
    return 1;
}

module.exports.foo = internal_foo;

and

// export_function.js

function internal_foo () {
    return 1;
}

module.exports = internal_foo;

When we run require('export_object.js') we get an object with a single function:

> const exp = require('./export_object.js')
undefined
> exp
{ foo: [Function: internal_foo] }

Compare that with the result we get when we run require('export_function.js'), where we just get a function:

> const exp = require('./export_funntion.js')
undefined
> exp
[Function: internal_foo]

When you configure AWS Lambda to run a function called handler, that is exported in a module defined in the file index.js, here is an approximation of Amazon does when a function is called:

const handler_module = require('index.js');
return handler_module.handler(event, context, callback);

The important part there is the call to the handler function defined in the module.


I have used like this.

//index.js

const user = require('./user').user;
const handler = function (event, context, callback) {
  user.login(username, password)
    .then((success) => {
      //success
    })
    .catch(() => {
      //error
    });
};

exports.handler = handler;



//user.js
const user = {
  login(username, password) {
   return new BPromise((resolve, reject) => {
     //do what you want.
   });
  }
};
export {user};

You need to define or export your handler function.

exports.handler = (username, password) => {
    ...
}