简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM