dinnouti
dinnouti

Reputation: 1796

How to load a lib folder in aws lambda?

In Serverless, I have the following folder structure

/component_a/function_1/function_1.js
/component_a/lib/util.js

When I try to load util.js from function_1.js using

u = require('../lib/util.js')

it works from the serverless CLI "serverless function run function_1". However in lambda/api-gateway it cannot find lib/util.js .

This is the error "Error: Cannot find module '../lib/util'"

How can I fix it?

Upvotes: 4

Views: 3671

Answers (1)

dinnouti
dinnouti

Reputation: 1796

This is how to fix. In the component_a/s-function.json replace

"handler": "handler.handler",

with

"handler": "component_a/handler.handler",

in the function_1.js call the util.js like

u = require('../lib/util')

from the Serverless documentation

The handler property gives you the ability to share code between your functions. By default the handler property is handler.handler, that means it's only relative to the function folder, so only the function folder will be deployed to Lambda.

If however you want to include the parent subfolder of a function, you should change the handler to be like this: functionName/handler.handler As you can see, the path to the handler now includes the function folder, which means that the path is now relative to the parent subfolder, so in that case the parent subfolder will be deployed along with your function. So if you have a lib folder in that parent subfolder that is required by your function, it'll be deployed with your function.

This also gives you the ability to handle npm dependencies however you like. If you have a package.json and node_modules in that parent subfolder, it'll be included in the deployed lambda. So the more parent folders you include in the handler path, the higher you go in the file tree.

Upvotes: 3

Related Questions