0

Context

I am working on a Lambda function in my index.js file to help me add watermark on images using Sharp.

This is the error I am getting.

2022-04-01T20:33:49.269Z    undefined   ERROR   Uncaught Exception  {"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Invalid or unexpected token","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Invalid or unexpected token","   
   at _loadUserApp ._loadUserApp (/var/runtime/UserFunction.js:200:13 undefined)","   
   at Object.module.exports.load (/var/runtime/UserFunction.js:242:17 undefined)","   
   at Object.<anonymous> (/var/runtime/index.js:43:30 undefined)","   
   at Module._compile (internal/modules/cjs/loader.js:1085:14 undefined)","   
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10 undefined)","   
   at Module.load (internal/modules/cjs/loader.js:950:32 undefined)","   
   at Function.Module._load (internal/modules/cjs/loader.js:790:12 undefined)","   
   at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12 undefined)","    at internal/main/run_main_module.js:17:47"]}

The Culprit

I realized the issue was happening when I imported a .png file.

const sharp = require('sharp');
const { S3 } = require('aws-sdk');
const stream = require('stream');
const playButtonPng = require('./assets/playButton.png'); // When this is commented out, the Lambda works

I thought about maybe "pulling" this image from S3, but it becomes complex since Sharp requires a "real image."

So my question is: is it possible to import a local .png in a lambda function? I tried investigating but did not find any results.

Other Things I've tried:

  • Using CommonJS imports
  • Configuring Lambda to use Node 14.x as I am using v14.18.3 locally
  • Double checking syntax. Using Babel to compile.
  • Adjusting the sharp node_module for production. (I don't think this was ever the issue).

I've also looked at these threads, which suggested

dsomel21
  • 576
  • 2
  • 8
  • 27
  • 1
    Yes, you can bundle a PNG or other assets when packaging a Lambda function. You're not going to be able to `require` that file, however, because it's a PNG, not a Node.js module. Just use regular file access. BTW it's unusual to see a Lambda function hosting or serving image files. Typically you would use S3. – jarmod Apr 01 '22 at 20:49

1 Answers1

1

load PNG file by readFile / readFileSync available in fs module.

var fs = require('fs')
const playButtonPng = fs.readFileSync('./assets/playButton.png')
  • Thank you! As @jarmod suggested, this is what I plan to do. `readFileSync` returns a buffer, but luckily, Sharp can support that! – dsomel21 Apr 01 '22 at 21:03