soldair / node-qrcode

qr code generator
MIT License
7.46k stars 621 forks source link

TypeError: import_qrcode.default.toBuffer is not a function when running in Cloudflare Workers #376

Open vladinator1000 opened 2 weeks ago

vladinator1000 commented 2 weeks ago

Hi there, it seems like the library doesn't work on Cloudflare even with the compatibility flags in wrangler.toml: compatibility_flags = ["nodejs_compat_v2"]

Steps to reproduce:

  1. Clone this repo: https://github.com/vladinator1000/cf-qrcode
  2. Run npm start
  3. Go to localhost:8787

I can see that toBuffer is clearly exported from https://github.com/soldair/node-qrcode/blob/master/lib/server.js#L106 I wonder if the issue is due to the bundling process. When I enumerate the package keys like this

import QRCode from 'qrcode';

export default {
    async fetch(request, env, ctx): Promise<Response> {
        return new Response(Object.keys(QRCode));
    },
} satisfies ExportedHandler<Env>;

I get

create,toCanvas,toDataURL,toString
vladinator1000 commented 2 weeks ago

I managed to get it to work by importing directly from the server folder

import { toBuffer } from 'qrcode/lib/server'

// Bonus promisification
export async function getQrCodeData(url: string): Promise<Buffer> {
  return new Promise((resolve, reject) => {
    function callback(err: Error, result: Buffer) {
      if (err) {
        reject(err)
      } else {
        resolve(result)
      }
    }

    toBuffer(url, callback)
  })
}