serverless-esbuild icon indicating copy to clipboard operation
serverless-esbuild copied to clipboard

Using node lib that imports files with fs.readFileSync throws error

Open andidev opened this issue 3 years ago • 1 comments

First I think this issue may maybe belong somewhere else. But I am not sure where and clueless in how to solve it.

I am trying to use node library conekta-node but when using it I get the following error:

{
  errno: -2,
  syscall: 'open',
  code: 'ENOENT',
  path: '/Users/ben/Workspace/myserver/.esbuild/.build/cert/ca_bundle.crt'
}

and the reason is because these lines in code in node_modules

const certPath = path.join(path.dirname(__dirname), '/cert/ca_bundle.crt')
...
ca: fs.readFileSync(certPath),

https://github.com/conekta/conekta-node/blob/master/lib/Requestor.js#L35

I tried

custom:
  esbuild:
    external:
      - conekta

but it leads to other problems about other modules not being available.

I also tried

custom:
  esbuild:
    packagerOptions:
      scripts:
        - mkdir -p .esbuild/.build/cert
        - cp node_modules/conekta/cert/ca_bundle.crt .esbuild/.build/cert/ca_bundle.crt

but does not seem to copy ca_bundle.crt file

I searched everywhere for a solution but can't find any.

Any hints?

andidev avatar Oct 31 '22 13:10 andidev

Have you tried adding your file as part of the package options on serverless.yml?

So something like: package: patterns: - 'node_modules/conekta/cert/ca_bundle.crt'

I usually use this and the files are added to the built package.

Davilopesm avatar Jan 23 '23 10:01 Davilopesm

Thanks for the advice that did almost work. Since esbuild bundles the code it cannot be included in node_modules folder

Was easily solved with esbuild-plugin-copy like this

/* eslint-disable @typescript-eslint/no-var-requires */
const { copy } = require('esbuild-plugin-copy');

module.exports = (serverless) => {
    return {
        minify: true,
        exclude: ['@aws/sdk'],
        bundle: true,
        sourcemap: true,
        keepNames: true,
        plugins: [
            copy({
                resolveFrom: 'cwd',
                assets: [
                    {
                        from: ['node_modules/conekta/cert/ca_bundle.crt'],
                        to: '.esbuild/.build/cert/ca_bundle.crt',
                    },
                ],
            }),
        ],
    };
};

andidev avatar Sep 06 '24 10:09 andidev