Reputation: 163
I'm creating a NodeJS service with serverless framework to validate a feed so I added a schema file (.json) to the service but I can’t make it work. It seems to not be included in the package. Lambda doesn't find that file.
First I just run sls package and check the zip contents but the file is not present. I also tried to include the file with:
package:
include:
- libs/schemas/schema.json
but still not works.
How can I make sure a static file is included in the package and can be read inside the lambda function?
Upvotes: 14
Views: 10065
Reputation: 259
For those struggling to find a solution in 2022: use package.patterns parameter. Example:
package:
patterns:
- libs/schemas/schema.json
- !libs/schemas/schema-prod.json
(!
in front of the file path excludes specified pattern)
Documentation: https://www.serverless.com/framework/docs/providers/aws/guide/packaging
Upvotes: 5
Reputation: 3232
From what I've found you can do this in many ways:
As it is stated in another answer: if you are using webpack you need to use a webpack plugin to include files in the lambda zip file
If you are not using webpack, you can use serverless package commnad (include/exclude).
You can create a layer and reference it from the lambda (the file will be in /opt/<layer_name>
. Take in consideration that as today (Nov20) I haven't found a way of doing this if you are using serverless.ts
without publishing the layer first (lambda's layer property is an ARN string and requires the layer version).
If your worried about security you can use AWS Secrets as it is stated in this answer.
You can do what @rsp says and include it in your code.
Upvotes: 3
Reputation: 111506
It depends on how you are actually trying to load the file.
Are you loading it with fs.readFile
or fs.readFileSync
?
In that case, Serverless doesn't know that you're going to need it. If you add a hint for Serverless to include that file in the bundle then make sure that you know where it is relative to your current working directory or your __dirname
.
Are you loading it with require()
? (Do you know that you can use require()
to load JSON files?) In that case, Serverless should know that you need it, but you still need to make sure that you got the path right.
If all else fails then you can always use a dirty hack. For example if you have a file 'x.json' that contains:
{
"a": 1,
"b": 2
}
then you can change it to an x.js
file that contains:
module.exports = {
"a": 1,
"b": 2
};
that you can load just like any other .js file, but it's a hack.
Upvotes: 3