node-qrcode

qr code generator

README

node-qrcode

QR code/2d barcode generator.

Travis npm npm npm

- API

Highlights

- Works on server and client (and react native with svg)
- CLI utility
- Save QR code as image
- Support for Numeric, Alphanumeric, Kanji and Byte mode
- Support for mixed modes
- Support for chinese, cyrillic, greek and japanese characters
- Support for multibyte characters (like emojis :smile:)
- Auto generates optimized segments for best data compression and smallest QR Code size
- App agnostic readability, QR Codes by definition are app agnostic

Installation

Inside your project folder do:

  1. ``` sh
  2. npm install --save qrcode
  3. ```

or, install it globally to use qrcode from the command line to save qrcode images or generate ones you can view in your terminal.

  1. ``` sh
  2. npm install -g qrcode
  3. ```

Usage

CLI


  1. ```
  2. Usage: qrcode [options] <input string>

  3. QR Code options:
  4.   -v, --qversion  QR Code symbol version (1 - 40)                       [number]
  5.   -e, --error     Error correction level           [choices: "L", "M", "Q", "H"]
  6.   -m, --mask      Mask pattern (0 - 7)                                  [number]

  7. Renderer options:
  8.   -t, --type        Output type                  [choices: "png", "svg", "utf8"]
  9.   -w, --width       Image width (px)                                    [number]
  10.   -s, --scale       Scale factor                                        [number]
  11.   -q, --qzone       Quiet zone size                                     [number]
  12.   -l, --lightcolor  Light RGBA hex color
  13.   -d, --darkcolor   Dark RGBA hex color
  14.   --small  Output smaller QR code to terminal                          [boolean]

  15. Options:
  16.   -o, --output  Output file
  17.   -h, --help    Show help                                              [boolean]
  18.   --version     Show version number                                    [boolean]

  19. Examples:
  20.   qrcode "some text"                    Draw in terminal window
  21.   qrcode -o out.png "some text"         Save as png image
  22.   qrcode -d F00 -o out.png "some text"  Use red as foreground color
  23. ```
If not specified, output type is guessed from file extension.
Recognized extensions are png, svg and txt.

Browser

node-qrcode can be used in browser through module bundlers like Browserify and Webpack or by including the precompiled bundle present inbuild/ folder.

Module bundlers

  1. ``` html
  2. <html>
  3.   <body>
  4.     <canvas id="canvas"></canvas>
  5.     <script src="bundle.js"></script>
  6.   </body>
  7. </html>
  8. ```

  1. ``` js
  2. // index.js -> bundle.js
  3. var QRCode = require('qrcode')
  4. var canvas = document.getElementById('canvas')

  5. QRCode.toCanvas(canvas, 'sample text', function (error) {
  6.   if (error) console.error(error)
  7.   console.log('success!');
  8. })
  9. ```

Precompiled bundle

  1. ``` html
  2. <canvas id="canvas"></canvas>
  3. <script src="/build/qrcode.js"></script>
  4. <script>
  5.   QRCode.toCanvas(document.getElementById('canvas'), 'sample text', function (error) {
  6.     if (error) console.error(error)
  7.     console.log('success!');
  8.   })
  9. </script>
  10. ```

If you install through npm, precompiled files will be available in node_modules/qrcode/build/ folder.


NodeJS

Require the module qrcode

  1. ``` js
  2. var QRCode = require('qrcode')

  3. QRCode.toDataURL('I am a pony!', function (err, url) {
  4.   console.log(url)
  5. })
  6. ```

render a qrcode for the terminal
  1. ``` js
  2. var QRCode = require('qrcode')

  3. QRCode.toString('I am a pony!',{type:'terminal'}, function (err, url) {
  4.   console.log(url)
  5. })
  6. ```

ES6/ES7

Promises and Async/Await can be used in place of callback function.

  1. ``` js
  2. import QRCode from 'qrcode'

  3. // With promises
  4. QRCode.toDataURL('I am a pony!')
  5.   .then(url => {
  6.     console.log(url)
  7.   })
  8.   .catch(err => {
  9.     console.error(err)
  10.   })

  11. // With async/await
  12. const generateQR = async text => {
  13.   try {
  14.     console.log(await QRCode.toDataURL(text))
  15.   } catch (err) {
  16.     console.error(err)
  17.   }
  18. }
  19. ```

Error correction level

Error correction capability allows to successfully scan a QR Code even if the symbol is dirty or damaged.
Four levels are available to choose according to the operating environment.

Higher levels offer a better error resistance but reduce the symbol's capacity.
If the chances that the QR Code symbol may be corrupted are low (for example if it is showed through a monitor)
is possible to safely use a low error level such as Low or Medium.

Possible levels are shown below:

LevelError
|------------------|:----------------:|
**L****~7%**
**M****~15%**
**Q****~25%**
**H****~30%**

The percentage indicates the maximum amount of damaged surface after which the symbol becomes unreadable.

Error level can be set through `options.errorCorrectionLevel` property.
If not specified, the default value is M.

  1. ``` js
  2. QRCode.toDataURL('some text', { errorCorrectionLevel: 'H' }, function (err, url) {
  3.   console.log(url)
  4. })
  5. ```

QR Code capacity

Capacity depends on symbol version and error correction level. Also encoding modes may influence the amount of storable data.

The QR Code versions range from version **1** to version **40**.
Each version has a different number of modules (black and white dots), which define the symbol's size.
For version 1 they are 21x21, for version 2 25x25 e so on.
Higher is the version, more are the storable data, and of course bigger will be the QR Code symbol.

The table below shows the maximum number of storable characters in each encoding mode and for each error correction level.

ModeLMQH
|--------------|------|------|------|------|
Numeric7089559639933057
Alphanumeric4296339124201852
Byte2953233116631273
Kanji181714351024784

Note: Maximum characters number can be different when using Mixed modes.

QR Code version can be set through `options.version` property.
If no version is specified, the more suitable value will be used. Unless a specific version is required, this option is not needed.

  1. ``` js
  2. QRCode.toDataURL('some text', { version: 2 }, function (err, url) {
  3.   console.log(url)
  4. })
  5. ```

Encoding modes

Modes can be used to encode a string in a more efficient way.
A mode may be more suitable than others depending on the string content.
A list of supported modes are shown in the table below:

ModeCharactersCompression
|--------------|-----------------------------------------------------------|-------------------------------------------|
Numeric0,3
Alphanumeric0–9,2
KanjiCharacters2
ByteCharactersEach

Choose the right mode may be tricky if the input text is unknown.
In these cases **Byte** mode is the best choice since all characters can be encoded with it. (See [Multibyte characters](#multibyte-characters))
However, if the QR Code reader supports mixed modes, using Auto mode may produce better results.

Mixed modes

Mixed modes are also possible. A QR code can be generated from a series of segments having different encoding modes to optimize the data compression.
However, switching from a mode to another has a cost which may lead to a worst result if it's not taken into account.
See Manual mode for an example of how to specify segments with different encoding modes.

Auto mode

By **default**, automatic mode selection is used.
The input string is automatically splitted in various segments optimized to produce the shortest possible bitstream using mixed modes.
This is the preferred way to generate the QR Code.

For example, the string ABCDE12345678?A1A will be splitted in 3 segments with the following modes:

SegmentMode
|----------|--------------|
ABCDEAlphanumeric
12345678Numeric
?A1AByte

Any other combinations of segments and modes will result in a longer bitstream.
If you need to keep the QR Code size small, this mode will produce the best results.

Manual mode

If auto mode doesn't work for you or you have specific needs, is also possible to manually specify each segment with the relative mode.
In this way no segment optimizations will be applied under the hood.
Segments list can be passed as an array of object:

  1. ``` js
  2.   var QRCode = require('qrcode')

  3.   var segs = [
  4.     { data: 'ABCDEFG', mode: 'alphanumeric' },
  5.     { data: '0123456', mode: 'numeric' }
  6.   ]

  7.   QRCode.toDataURL(segs, function (err, url) {
  8.     console.log(url)
  9.   })
  10. ```

Kanji mode

With kanji mode is possible to encode characters from the Shift JIS system in an optimized way.
Unfortunately, there isn't a way to calculate a Shifted JIS values from, for example, a character encoded in UTF-8, for this reason a conversion table from the input characters to the SJIS values is needed.
This table is not included by default in the bundle to keep the size as small as possible.

If your application requires kanji support, you will need to pass a function that will take care of converting the input characters to appropriate values.

An helper method is provided by the lib through an optional file that you can include as shown in the example below.

Note: Support for Kanji mode is only needed if you want to benefit of the data compression, otherwise is still possible to encode kanji using Byte mode (See Multibyte characters).

  1. ``` js
  2.   var QRCode = require('qrcode')
  3.   var toSJIS = require('qrcode/helper/to-sjis')

  4.   QRCode.toDataURL(kanjiString, { toSJISFunc: toSJIS }, function (err, url) {
  5.     console.log(url)
  6.   })
  7. ```

With precompiled bundle:

  1. ``` html
  2. <canvas id="canvas"></canvas>
  3. <script src="/build/qrcode.min.js"></script>
  4. <script src="/build/qrcode.tosjis.min.js"></script>
  5. <script>
  6.   QRCode.toCanvas(document.getElementById('canvas'),
  7.     'sample text', { toSJISFunc: QRCode.toSJIS }, function (error) {
  8.     if (error) console.error(error)
  9.     console.log('success!')
  10.   })
  11. </script>
  12. ```

Binary data

QR Codes can hold arbitrary byte-based binary data. If you attempt to create a binary QR Code by first converting the data to a JavaScript string, it will fail to encode propery because string encoding adds additional bytes. Instead, you must pass a [Uint8ClampedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) or compatible array, or a Node Buffer, as follows:

  1. ``` js
  2. // Regular array example
  3. // WARNING: Element values will be clamped to 0-255 even if your data contains higher values.
  4. const QRCode = require('qrcode')
  5. QRCode.toFile(
  6.   'foo.png',
  7.   [{ data: [253,254,255], mode: 'byte' }],
  8.   ...options...,
  9.   ...callback...
  10. )
  11. ```

  1. ``` js
  2. // Uint8ClampedArray example
  3. const QRCode = require('qrcode')

  4. QRCode.toFile(
  5.   'foo.png',
  6.   [{ data: new Uint8ClampedArray([253,254,255]), mode: 'byte' }],
  7.   ...options...,
  8.   ...callback...
  9. )
  10. ```

  1. ``` js
  2. // Node Buffer example
  3. // WARNING: Element values will be clamped to 0-255 even if your data contains higher values.
  4. const QRCode = require('qrcode')

  5. QRCode.toFile(
  6.   'foo.png',
  7.   [{ data: Buffer.from([253,254,255]), mode: 'byte' }],
  8.   ...options...,
  9.   ...callback...
  10. )
  11. ```

TypeScript users: if you are using @types/qrcode, you will need to add a// @ts-ignore above the data segment because it expects data: string.

Multibyte characters

Support for multibyte characters isn't present in the initial QR Code standard, but is possible to encode UTF-8 characters in Byte mode.

QR Codes provide a way to specify a different type of character set through ECI (Extended Channel Interpretation), but it's not fully implemented in this lib yet.

Most QR Code readers, however, are able to recognize multibyte characters even without ECI.

Note that a single Kanji/Kana or Emoji can take up to 4 bytes.

API

Browser:

Server:

Browser API

create(text, [options])

Creates QR Code symbol and returns a qrcode object.

text
Type: String|Array

Text to encode or a list of objects describing segments.

options

returns
Type: Object

  1. ``` js
  2. // QRCode object
  3. {
  4.   modules,              // Bitmatrix class with modules data
  5.   version,              // Calculated QR Code version
  6.   errorCorrectionLevel, // Error Correction Level
  7.   maskPattern,          // Calculated Mask pattern
  8.   segments              // Generated segments
  9. }
  10. ```

toCanvas(canvasElement, text, [options], [cb(error)])

toCanvas(text, [options], [cb(error, canvas)])

Draws qr code symbol to canvas.
If canvasElement is omitted a new canvas is returned.

canvasElement
Type: DOMElement

Canvas where to draw QR Code.

text
Type: String|Array

Text to encode or a list of objects describing segments.

options
See Options.

cb
Type: Function

Callback function called on finish.

Example
  1. ``` js
  2. QRCode.toCanvas('text', { errorCorrectionLevel: 'H' }, function (err, canvas) {
  3.   if (err) throw err

  4.   var container = document.getElementById('container')
  5.   container.appendChild(canvas)
  6. })
  7. ```

toDataURL(text, [options], [cb(error, url)])

toDataURL(canvasElement, text, [options], [cb(error, url)])

Returns a Data URI containing a representation of the QR Code image.
If provided, canvasElement will be used as canvas to generate the data URI.

canvasElement
Type: DOMElement

Canvas where to draw QR Code.

text
Type: String|Array

Text to encode or a list of objects describing segments.

options
- ###### type
Type: `String`
  Default: image/png

Data URI format.
Possible values are: `image/png`, `image/jpeg`, `image/webp`.

- ###### rendererOpts.quality
Type: `Number`
  Default: 0.92

  A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp.

See Options for other settings.

cb
Type: Function

Callback function called on finish.

Example
  1. ``` js
  2. var opts = {
  3.   errorCorrectionLevel: 'H',
  4.   type: 'image/jpeg',
  5.   quality: 0.3,
  6.   margin: 1,
  7.   color: {
  8.     dark:"#010599FF",
  9.     light:"#FFBF60FF"
  10.   }
  11. }

  12. QRCode.toDataURL('text', opts, function (err, url) {
  13.   if (err) throw err

  14.   var img = document.getElementById('image')
  15.   img.src = url
  16. })
  17. ```

toString(text, [options], [cb(error, string)])


Returns a string representation of the QR Code.


text
Type: String|Array

Text to encode or a list of objects describing segments.

options
- ###### type
Type: `String`
  Default: utf8

Output format.
  Possible values are: terminal,utf8, and svg.

See Options for other settings.

cb
Type: Function

Callback function called on finish.

Example
  1. ``` js
  2. QRCode.toString('http://www.google.com', function (err, string) {
  3.   if (err) throw err
  4.   console.log(string)
  5. })
  6. ```

Server API

create(text, [options])

See create.

toCanvas(canvas, text, [options], [cb(error)])

Draws qr code symbol to node canvas.

text
Type: String|Array

Text to encode or a list of objects describing segments.

options
See Options.

cb
Type: Function

Callback function called on finish.

toDataURL(text, [options], [cb(error, url)])

Returns a Data URI containing a representation of the QR Code image.
Only works with image/png type for now.

text
Type: String|Array

Text to encode or a list of objects describing segments.

options
See Options for other settings.

cb
Type: Function

Callback function called on finish.

toString(text, [options], [cb(error, string)])

Returns a string representation of the QR Code.
If choosen output format is svg it will returns a string containing xml code.

text
Type: String|Array

Text to encode or a list of objects describing segments.

options
- ###### type
Type: `String`
  Default: utf8

Output format.
  Possible values are: utf8, svg, terminal.

See Options for other settings.

cb
Type: Function

Callback function called on finish.

Example
  1. ``` js
  2. QRCode.toString('http://www.google.com', function (err, string) {
  3.   if (err) throw err
  4.   console.log(string)
  5. })
  6. ```

toFile(path, text, [options], [cb(error)])

Saves QR Code to image file.
If `options.type` is not specified, the format will be guessed from file extension.
Recognized extensions are png, svg, txt.

path
Type: String

Path where to save the file.

text
Type: String|Array

Text to encode or a list of objects describing segments.

options
- ###### type
Type: `String`
  Default: png

Output format.
  Possible values are: png, svg, utf8.

- ###### rendererOpts.deflateLevel (png only)
Type: `Number`
  Default: 9

  Compression level for deflate.

- ###### rendererOpts.deflateStrategy (png only)
Type: `Number`
  Default: 3

  Compression strategy for deflate.

See Options for other settings.

cb
Type: Function

Callback function called on finish.

Example
  1. ``` js
  2. QRCode.toFile('path/to/filename.png', 'Some text', {
  3.   color: {
  4.     dark: '#00F',  // Blue dots
  5.     light: '#0000' // Transparent background
  6.   }
  7. }, function (err) {
  8.   if (err) throw err
  9.   console.log('done')
  10. })
  11. ```

toFileStream(stream, text, [options])

Writes QR Code image to stream. Only works with png format for now.

stream
Type: stream.Writable

Node stream.

text
Type: String|Array

Text to encode or a list of objects describing segments.

options
See Options.

Options


QR Code options

version
Type: `Number`

  QR Code version. If not specified the more suitable value will be calculated.

errorCorrectionLevel
Type: `String`
  Default: M

Error correction level.
  Possible values are low, medium, quartile, high or L, M, Q, H.

maskPattern
Type: `Number`

Mask pattern used to mask the symbol.
Possible values are `0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`.
  If not specified the more suitable value will be calculated.

toSJISFunc
Type: `Function`

Helper function used internally to convert a kanji to its Shift JIS value.
  Provide this function if you need support for Kanji mode.

Renderers options

margin
Type: `Number`
  Default: 4

  Define how much wide the quiet zone should be.

scale
Type: `Number`
  Default: 4

  Scale factor. A value of 1 means 1px per modules (black dots).

small
Type: `Boolean`
  Default: false

  Relevant only for terminal renderer. Outputs smaller QR code.

width
Type: `Number`

Forces a specific width for the output image.
If width is too small to contain the qr symbol, this option will be ignored.
  Takes precedence over scale.

color.dark
Type: `String`
Default: #000000ff

Color of dark module. Value must be in hex format (RGBA).
Note: dark color should always be darker than color.light.

color.light
Type: `String`
Default: #ffffffff

Color of light module. Value must be in hex format (RGBA).

GS1 QR Codes

There was a real good discussion here about them. but in short any qrcode generator will make gs1 compatible qrcodes, but what defines a gs1 qrcode is a header with metadata that describes your gs1 information.

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


Credits

This lib is based on "QRCode for JavaScript" which Kazuhiko Arase thankfully MIT licensed.

License


The word "QR Code" is registered trademark of:
DENSO WAVE INCORPORATED