Hosting a file along with my functioncmn


I’d like to create a function which loads a PDF and performs some manipulations on it before returning it. I’ve put my PDF file in my functions directory but it seems that the built function is moved elsewhere before it’s served and the PDF is not taken with it. I can’t find any examples of doing a similar thing so is this just not possible?

With the following in my function:

const fs = require('fs')

I get the following error:

{"errorMessage":"ENOENT: no such file or directory, open 'dummy.pdf'","errorType":"Error","stackTrace":["Object.fs.openSync (fs.js:646:18)","Object.fs.readFileSync (fs.js:551:33)","e.handler (/var/task/hello.js:1:146237)"]}

Thanks ahead!

Problem solved. When using fs file paths are relative to the project root.

Actually, that’s only when serving locally - the file still cannot be read once deployed.

@voteymcvotefaceuk There is a way to handle this for both path resolution to be the same and get your assets into your function.

  • Put your function into a sub-directory under the folder you specified in your netlify.toml (i.e pdf-read.js would be put to `functions/pdf-read/pdf-read.js).
  • Include the assets in the functions/pdf-read folder
  • Change your path with require.resolve
    const contents = fs.readFileSync(require.resolve('./dummy.pdf'))

Working example in this repository to read a .txt file in the function under functions/read-file

Note: Remember, this is the target functions directory, not a source directory prior to a build. The example does not do a webpack functions build using netlify-lambda. That process would take a little more workflow to get the bundle and assets into the target location. As long as you are using nodejs javascript, this is a valid solution.

1 Like

Moving the static files my function depended on to a subdirectory along with the function itself worked beautifully, thank you!

Although I didn’t need to use require.resolve to get the filepath. Simply using fs.readFileSync('dummy.pdf') worked fine. Are you sure this step is necessary?