yabune
yabune

Reputation: 163

How to include static files on Serverless Framework?

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

Answers (3)

portik
portik

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

lmiguelmh
lmiguelmh

Reputation: 3232

From what I've found you can do this in many ways:

Upvotes: 3

rsp
rsp

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

Related Questions