Some modules can be used with NodejsFunction(AWS CDK) and some cannot?

Viewed 136

I defined a lambda function using NodejsFunction of AWS CDK.
I installed the modules I want to use in my lambda function in node_modules of CDK.
When I execute sam local invoke, some modules succeed and others fail.
When an error occurs, the error message "File not found in '/var/task/...'" is displayed.
Does this mean that some modules can be used with NodejsFunction and some cannot?

lambda-stack.ts

new lambda.NodejsFunction(this, 'SampleFunction', {
  runtime: Runtime.NODEJS_14_X,
  entry: 'lambda/sample-function/index.ts'
})

lambda/sample-function/index.ts (use 'date-fns') -> succeeded!

import { format } from 'date-fns'

export const handler = async () => {
  try {
    console.log(format(new Date(), "'Today is a' eeee"))
  } catch (error) {
    console.log(error)
  }
}

lambda/sample-function/index.ts (use 'chrome-aws-lambda') -> failed

const chromium = require('chrome-aws-lambda')

export const handler = async () => {
  try {
    const browser = await chromium.puppeteer.launch()
  } catch (error) {
    // Cannot find module '/var/task/puppeteer/lib/Browser'
    console.log(error)
  }
}

lambda/sample-function/index.ts (use 'pdfkit') -> failed

const PDFDocument = require('pdfkit')

export const handler = async () => {
  try {
    const doc = new PDFDocument()
  } catch (error) {
    // no such file or directory, open '/var/task/data/Helvetica.afm'
    console.log(error)
  }
}
1 Answers

it seems that the "pdfkit" and "chrome-aws-lambda" are packages that use some binary files and you need to verify that those binary found in lambda.

when you create a lambda using 'new lambda.NodejsFunction()' in background, there is a esbuild process that bundles all files into one so make sure you not see any error related to that build during synth.

in order to verfiy this is the problem you could try upload your lambda with node_modules and chcek if it is work.

alternative you can:

  • look (or create) "lambda layer" that will contain those binary see example.
  • build your lambda with all of the dependencies as a docker image and set lambda to run that docker.
Related