node-qrcode

repository·master·Indexed 27 days ago

https://github.com/soldair/node-qrcode

A QR code and 2D barcode generator for Node.js and browser environments (version 1.5.4). It supports various encoding modes (Numeric, Alphanumeric, Kanji, Byte) and provides a CLI for generating codes in the terminal or as images (PNG, SVG). Key features include support for Promises and async/await, configurable error correction levels (L, M, Q, H), and methods to render QR codes to HTML canvas, Data URLs, files, or streams.

Tokens
3.4K
Snippets
12
Records
29
Agent score
90%

What's inside node-qrcode

  1. Use node-qrcode in the Browser

    master

    You can use node-qrcode in the browser via module bundlers (Webpack, Browserify) or by including the precompiled bundle from the build/ folder. The toCanvas method is commonly used to render the QR code onto an HTML <canvas> element.

    // Using a precompiled bundle
    <canvas id="canvas"></canvas>
    <script src="/build/qrcode.js"></script>
    <script>
      QRCode.toCanvas(document.getElementById('canvas'), 'sample text', function (error) {
        if (error) console.error(error)
        console.log('success!');
      })
    </script>
  2. Encode binary data in QR Codes

    master

    To encode arbitrary byte-based binary data, do not convert the data to a JavaScript string as this adds extra bytes and will cause encoding errors. Instead, pass a Uint8ClampedArray, a Node Buffer, or a regular array of bytes as a list of segments using the mode: 'byte' option.

    Note for TypeScript users: If using @types/qrcode, you may need to add // @ts-ignore above the data segment because the types expect a string.

    // Uint8ClampedArray example
    const QRCode = require('qrcode')
    
    QRCode.toFile(
      'foo.png',
      [{ data: new Uint8ClampedArray([253,254,255]), mode: 'byte' }],
      ...options...,
      ...callback...
    )
  3. Configure Error Correction Level

    master

    Error correction allows the QR code to be scanned even if damaged. You can set this via the options.errorCorrectionLevel property. The default is M.

    Available levels:

    • L (Low): ~7% error resistance
    • M (Medium): ~15% error resistance
    • Q (Quartile): ~25% error resistance
    • H (High): ~30% error resistance
    QRCode.toDataURL('some text', { errorCorrectionLevel: 'H' }, function (err, url) {
      console.log(url)
    })
  4. Configure QR Code Version

    master

    The QR Code version (1 to 40) determines the number of modules (size) and capacity. If not specified, the library automatically selects the most suitable version. Set it via options.version.

    QRCode.toDataURL('some text', { version: 2 }, function (err, url) {
      console.log(url)
    })
  5. Configure QR Code Options

    master

    When generating QR Codes, you can pass an options object to control the encoding parameters.

    QR Code Options:

    • version: QR Code version. If not specified, the most suitable value is calculated.
    • errorCorrectionLevel: Error correction level. Values: low, medium, quartile, high or L, M, Q, H. Default is M.
    • maskPattern: Mask pattern used to mask the symbol. Values: 0 through 7. If not specified, the most suitable value is calculated.
    • toSJISFunc: A helper function used internally to convert a kanji to its Shift JIS value. Provide this if you need support for Kanji mode.
  6. Configure Renderer Options

    master

    Renderer options control the visual appearance of the generated QR Code.

    Visual Options:

    • margin: Defines how wide the quiet zone should be. Default is 4.
    • scale: Scale factor. A value of 1 means 1px per module (black dot). Default is 4.
    • small: (Terminal renderer only) Outputs a smaller QR code. Default is false.
    • width: Forces a specific width for the output image. Takes precedence over scale. If the width is too small to contain the symbol, this option is ignored.
    • color.dark: Color of dark module. Must be in hex format (RGBA). Default is #000000ff. Note: dark color should always be darker than color.light.
    • color.light: Color of light module. Must be in hex format (RGBA). Default is #ffffffff.
  7. Use Promises and Async/Await with node-qrcode

    master

    For ES6/ES7 environments, you can use Promises or async/await instead of traditional callbacks.

    import QRCode from 'qrcode'
    
    // With promises
    QRCode.toDataURL('I am a pony!')
      .then(url => {
        console.log(url)
      })
      .catch(err => {
        console.error(err)
      })
    
    // With async/await
    const generateQR = async text => {
      try {
        console.log(await QRCode.toDataURL(text))
      } catch (err) {
        console.error(err)
      }
    }
  8. Generate a Data URI from a QR Code

    master

    Use toDataURL() to get a Data URI representing the QR Code image.

    Browser usage:

    • toDataURL(text, [options], [cb(error, url)])
    • toDataURL(canvasElement, text, [options], [cb(error, url)]): Uses the provided canvas to generate the URI.
    • Options:
      • type: Data URI format (image/png, image/jpeg, image/webp). Default is image/png.
      • rendererOpts.quality: A number between 0 and 1 (used for image/jpeg or image/webp). Default is 0.92.

    Server usage:

    • toDataURL(text, [options], [cb(error, url)]): Currently only supports image/png on the server.
    var opts = {
      errorCorrectionLevel: 'H',
      type: 'image/jpeg',
      quality: 0.3,
      margin: 1,
      color: {
        dark:"#010599FF",
        light:"#FFBF60FF"
      }
    }
    
    QRCode.toDataURL('text', opts, function (err, url) {
      if (err) throw err
    
      var img = document.getElementById('image')
      img.src = url
    })
  9. Draw QR Code to a Canvas

    master

    Use toCanvas() to draw a QR Code onto a canvas element.

    Browser usage:

    • toCanvas(canvasElement, text, [options], [cb(error)]): Draws to a specific DOMElement.
    • toCanvas(text, [options], [cb(error, canvas)]): If canvasElement is omitted, a new canvas is returned.

    Server usage:

    • toCanvas(canvas, text, [options], [cb(error)]): Draws to a node-canvas instance.
    QRCode.toCanvas('text', { errorCorrectionLevel: 'H' }, function (err, canvas) {
      if (err) throw err
    
      var container = document.getElementById('container')
      container.appendChild(canvas)
    })