GithubHelp home page GithubHelp logo

node-qrcode's Introduction

node-qrcode

QR code/2d barcode generator.

Travis npm npm npm

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 😄)
  • 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:

npm install --save qrcode

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

npm install -g qrcode

Usage

CLI

Usage: qrcode [options] <input string>

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

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

Options:
  -o, --output  Output file
  -h, --help    Show help                                              [boolean]
  --version     Show version number                                    [boolean]

Examples:
  qrcode "some text"                    Draw in terminal window
  qrcode -o out.png "some text"         Save as png image
  qrcode -d F00 -o out.png "some text"  Use red as foreground color

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 in build/ folder.

Module bundlers

<!-- index.html -->
<html>
  <body>
    <canvas id="canvas"></canvas>
    <script src="bundle.js"></script>
  </body>
</html>
// index.js -> bundle.js
var QRCode = require('qrcode')
var canvas = document.getElementById('canvas')

QRCode.toCanvas(canvas, 'sample text', function (error) {
  if (error) console.error(error)
  console.log('success!');
})

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>

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

The precompiled bundle have support for Internet Explorer 10+, Safari 5.1+, and all evergreen browsers.

NodeJS

Require the module qrcode

var QRCode = require('qrcode')

QRCode.toDataURL('I am a pony!', function (err, url) {
  console.log(url)
})

render a qrcode for the terminal

var QRCode = require('qrcode')

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

ES6/ES7

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

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)
  }
}

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:

Level Error resistance
L (Low) ~7%
M (Medium) ~15%
Q (Quartile) ~25%
H (High) ~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.

QRCode.toDataURL('some text', { errorCorrectionLevel: 'H' }, function (err, url) {
  console.log(url)
})

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.

Mode L M Q H
Numeric 7089 5596 3993 3057
Alphanumeric 4296 3391 2420 1852
Byte 2953 2331 1663 1273
Kanji 1817 1435 1024 784

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.

QRCode.toDataURL('some text', { version: 2 }, function (err, url) {
  console.log(url)
})

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:

Mode Characters Compression
Numeric 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 3 characters are represented by 10 bits
Alphanumeric 0–9, A–Z (upper-case only), space, $, %, *, +, -, ., /, : 2 characters are represented by 11 bits
Kanji Characters from the Shift JIS system based on JIS X 0208 2 kanji are represented by 13 bits
Byte Characters from the ISO/IEC 8859-1 character set Each characters are represented by 8 bits

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)
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:

Segment Mode
ABCDE Alphanumeric
12345678 Numeric
?A1A Byte

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:

  var QRCode = require('qrcode')

  var segs = [
    { data: 'ABCDEFG', mode: 'alphanumeric' },
    { data: '0123456', mode: 'numeric' }
  ]

  QRCode.toDataURL(segs, function (err, url) {
    console.log(url)
  })

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).

  var QRCode = require('qrcode')
  var toSJIS = require('qrcode/helper/to-sjis')

  QRCode.toDataURL(kanjiString, { toSJISFunc: toSJIS }, function (err, url) {
    console.log(url)
  })

With precompiled bundle:

<canvas id="canvas"></canvas>

<script src="/build/qrcode.min.js"></script>
<script src="/build/qrcode.tosjis.min.js"></script>
<script>
  QRCode.toCanvas(document.getElementById('canvas'),
    'sample text', { toSJISFunc: QRCode.toSJIS }, function (error) {
    if (error) console.error(error)
    console.log('success!')
  })
</script>

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 or compatible array, or a Node Buffer, as follows:

// Regular array example
// WARNING: Element values will be clamped to 0-255 even if your data contains higher values.
const QRCode = require('qrcode')
QRCode.toFile(
  'foo.png',
  [{ data: [253,254,255], mode: 'byte' }],
  ...options...,
  ...callback...
)
// Uint8ClampedArray example
const QRCode = require('qrcode')

QRCode.toFile(
  'foo.png',
  [{ data: new Uint8ClampedArray([253,254,255]), mode: 'byte' }],
  ...options...,
  ...callback...
)
// Node Buffer example
// WARNING: Element values will be clamped to 0-255 even if your data contains higher values.
const QRCode = require('qrcode')

QRCode.toFile(
  'foo.png',
  [{ data: Buffer.from([253,254,255]), mode: 'byte' }],
  ...options...,
  ...callback...
)

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

See QR Code options.

returns

Type: Object

// QRCode object
{
  modules,              // Bitmatrix class with modules data
  version,              // Calculated QR Code version
  errorCorrectionLevel, // Error Correction Level
  maskPattern,          // Calculated Mask pattern
  segments              // Generated segments
}

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
QRCode.toCanvas('text', { errorCorrectionLevel: 'H' }, function (err, canvas) {
  if (err) throw err

  var container = document.getElementById('container')
  container.appendChild(canvas)
})

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
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
})

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
QRCode.toString('http://www.google.com', function (err, string) {
  if (err) throw err
  console.log(string)
})

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
QRCode.toString('http://www.google.com', function (err, string) {
  if (err) throw err
  console.log(string)
})

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
QRCode.toFile('path/to/filename.png', 'Some text', {
  color: {
    dark: '#00F',  // Blue dots
    light: '#0000' // Transparent background
  }
}, function (err) {
  if (err) throw err
  console.log('done')
})

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.

#45

Credits

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

License

MIT

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

node-qrcode's People

Contributors

aldonline avatar aug2uag avatar benallfree avatar dannysu09 avatar fatelei avatar freewil avatar heartnetkung avatar joemccann avatar jvanaert avatar kennedybaird avatar kevinahuber avatar kochie avatar linusu avatar lixiaoyan avatar nerdyman avatar niftylettuce avatar renovatingdev avatar samuelterra22 avatar soldair avatar spro avatar supericeboy avatar tbusser avatar tenjaa avatar thinkroth avatar tietew avatar vicjohnson1213 avatar vigreco avatar wemakeweb avatar wnger avatar yzwduck avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-qrcode's Issues

Having an issue installing it?

npm install --save node-qrcode

It hangs(?) on the loading webDrivers step.

npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
npm WARN deprecated [email protected]: lodash@<3.0.0 is no longer maintained. Upgrade to lodash@^4.0.0.

> [email protected] install /Users/rstudner/projects/auth-api/node_modules/node-browser
> node ./build.js

load: download webDrivers...

Not saving file

Hi,

I'm trying to save a QR Code into a './tmp/example.png' file but I'm not getting either the file or an error message.

var jungleBook = "Javiii loves coffee";

    //QRCode.QRCodeDraw.color.dark = '#d4d4d4';
    QRCode.save('./tmp/example.png',jungleBook,function(err,url){
        if(err) console.log('error: '+err);
    });

What am I doing wrong?

Thanks!

errorCorrectLevel medium as max

I've been testing and it seems that generating QR with medium as errorCorrectLevel option results in H error correction level in state of M.

var QRCode = require('qrcode');
var opts = {errorCorrectLevel: "medium"};
QRCode.save('qr.png', 'foo', opts);

qr

GS1 QR code

Hi there!

Can we create gs1 qr code.

Thankz.

Using the lib from node, browser methods still being called.

Hello!

I've been trying to use the lib from node.js and I was under the impression that making method calls from node.js would use the functions in server.js but I keep getting this error where the lib complains about a canvasElement being required, which, from looking at the souce code, I think it's only a requirement of the browser lib. I also digged the code expecting to find where a fallback to the broser code would happen but I wasn't able to see such fallback anywhere.

Any help is greatly appreciated :)

Cheers!

var QRCode = require("qrcode")
QRCode.toDataURL("test", {type: "png"}, function(err, url) {
  console.log(err) // Error: You need to specify a canvas element
  console.log(url) // undefined
})

Full disclosure: I'm not simply using it from node, but on a react-native project; this is because I haven't been able to find a good RN solution to create QRCodes that actually passes builds and/or is maintained. If this lib can't be used at all from RN I'd be most thankful if you could point me in the right direction.

QRCode.draw fails with data smaller than the supported capacity

Hi All,
I have read soldair's docs here specifying that the QR codes generated by this library are 'level H' whose max capacity is 1,273 characters.

The library though fails occasionally when trying to encode smaller strings and returns Canvas objects that render to empty png files. Experimentally, I managed to make this happen with as little as 1,269 characters.

This gist has everything that is needed to reproduce the issue.

Giacecco

Installation section issue

When build node-qrcode, it need libgif-dev. But the doc doesn't mention it.

Change:

sudo apt-get install libpixman-1-dev libcairo2-dev libpangocairo-1.0-0 libpango1.0-dev

To:

sudo apt-get install libpixman-1-dev libcairo2-dev libpangocairo-1.0-0 libpango1.0-dev libgif-dev

qrcode.toCanvas with wrong

version :0.8.1
my nodejs server on exec qr.code.toCanvas(text,opts,cb) is wrong!!!!
this response :Error: You need to specify a canvas element

on canvas.js function getCanvasElement ()
on browser is ok
on server is not work

this code is

function getCanvasElement () {
  try {
    return document.createElement('canvas')
  } catch (e) {
    throw new Error('You need to specify a canvas element')
  }
}

change into

function getCanvasElement () {
  try {
   //check nodejs env
   if(module && module.exports){
      var Canvas = require('canvas');

      return new Canvas();
    }
    // browser env
    return document.createElement('canvas')
  } catch (e) {
    throw new Error('You need to specify a canvas element')
  }
}

Refactor proposal and possible future enhancements

I open this issue to discuss about a possible re-factor of the lib.

The main reason that led me to propose this is because I found quite hard right now add tests or new functionalities to the lib in a clean way.

I started adding unit tests in my local branch but it's hard to follow what tests are actually testing.

I've also some ideas (mostly regarding the rendering part) that I would like to share and see implemented here but since most of the logic and rendering part is all contained in a couple of files, add new code there will lead at some point to more confusion and to a code harder to manage.

So, I propose these change:

Split qrcode.js file in smaller modules

Having small, simple modules each with its own task, will make much easier add tests, documentation and new functionalities to them, and will make code easier to follow.
Add support for other qrcode types would be also easier.

Remove duplicated code and organize renderers

Currently, most of the code that is used to draw the qrcode is duplicated across various functions and it's hard to test.
A more 'composable' structure could help to organize the various renderers.
We could have a base-renderer class that will contains all the common methods and then a list of possible renderer.

The file structure so far could be something like:

lib/
  core/
    8bit-byte.js
    alignment-pattern.js
    bit-buffer.js
    ecc.js
    finder-pattern.js
    mask-pattern.js
    math.js
    modes.js
    polynomial.js
    rs-blocks.js
    utils.js
    version.js
  renderer/
    base-renderer.js
    png-renderer.js
    jpg-renderer.js
    svg-renderer.js
    pdf-renderer.js
    canvas-renderer.js
    terminal-renderer.js
  qrcode.js

Add linter and code coverage

Since one of the main reason of this refactor is to promote the add of tests, having code coverage would also be helpful.
Also, enforcing code style with a linter will prevent common bugs and style inconsistency across files.
I would suggest eslint with something like Standard JS.

(Future work) Remove node-canvas in place of image libs

I think node-canvas is a bit overkill if used to just export images.
Renderer like png-renderer.js and jpg-renderer.js could take advantages of dedicated image libs like pngjs and jpeg-js

(Future work) Completely decouple logic from render

Currently the qrcode.js lib, takes care of generating the qrcode data and rendering it as an array of bit representing each modules.
This array is then used to draw the qrcode and export it as image.
This works perfectly fine, but I would like to abstract a little more this process and split the drawing methods in smaller parts.

The idea is to move all the function that do something related to how to render in (for example) base-renderer.js and let core library to just produce information (such as coords) about what and where to render.
base-renderer would have dedicated functions to render for example: qrcode background, finding pattern, alignment pattern, each single modules ecc.
These functions could be then extended/overriden to add support for effects, such as colors or deformations to allow qrcode customization (like this)

(Future work) Add support for promise

I think Promises support would also be a good addition to the lib.

What do you think?

retina friendly

Is it possible to add scaling depending on devicePixelRatio for the browser renderer?

toFileStream silent failure with too large string

// big_string is about 2 ^ 16 - 1 characters in length
var big_string = get_big_string_somehow()
var stream = get_writable_stream_somehow()
qr.toFileStream(stream, big_string, console.log)

when this is program is run, console.log is never invoked. what i expected is console.log to be invoked with an error describing that there is too much input data to be encoded.

note that i'm not sure exactly how big the string has to be to cause the silent failure, but the project in which i am using this library was attempting to use a string of more or less that size.

fs.write bad argument on Heroku

node-qrcode works perfecly on my MAC but when I deploy my app on heroku I've got an error :

2013-10-11T17:41:10.282649+00:00 app[web.1]: fs.js:513
2013-10-11T17:41:10.282928+00:00 app[web.1]:   binding.write(fd, buffer, offset, length, position, wrapper);
2013-10-11T17:41:10.284816+00:00 app[web.1]: TypeError: Bad argument
2013-10-11T17:41:10.284816+00:00 app[web.1]:     at fdAndBuf (/app/node_modules/qrcode/qrcode.js:133:7)
2013-10-11T17:41:10.284816+00:00 app[web.1]:     at args.(anonymous function) (/app/node_modules/nodetime/lib/core/proxy.js:131:20)
2013-10-11T17:41:10.284816+00:00 app[web.1]:     at /app/node_modules/qrcode/qrcode.js:150:12
2013-10-11T17:41:10.284816+00:00 app[web.1]:     at Object.oncomplete (fs.js:107:15)
2013-10-11T17:41:10.284816+00:00 app[web.1]:     at Object.fs.write (fs.js:513:11)
2013-10-11T17:41:10.284816+00:00 app[web.1]:     at Object.obj.(anonymous function) [as write] (/app/node_modules/nodetime/lib/core/proxy.js:45:19)
2013-10-11T17:41:12.024784+00:00 heroku[web.1]: Process exited with status 8

Uint32Array error on android devices

when i load on client side the script /assets/qrcode.js on line 651 i have this console error

Uncaught ReferenceError: Uint32Array is not defined

can you explain me whats the problem what im doing wrong?

unable to install without jpeglib-dev on ubuntu

Thanks for a good package, I followed your instructions:

sudo apt-get install libpixman-1-dev libcairo2-dev libpangocairo-1.0-0 libpango1.0-dev libgif-dev

I didnt got it to work before I realized that I needed to install the libjpeg-dev package.

Maybe I didnt do it right the first time but I maybe this info helps someone else!

Weird issue impact regarding String.bold() Javascript

Hi everyone!

This is really weird issue we've in our project...
Some places (in node.js) we use bold() to return some kind of HTML strings (I know this is a bad practice, by the way).
The thing is: when you require QRCode .bold() method stops working

You can test this usign node cli

$ node
> 'teste'.bold()
'<b>teste</b>'
> require('qrcode')
{ create: [Function: create],
  toCanvas: [Function: bound renderCanvas],
  toString: [Function: toString],
  toDataURL: [Function: toDataURL],
  toFile: [Function: toFile],
  toFileStream: [Function: toFileStream],
  drawText: [Function: toString],
  drawSvg: [Function],
  drawPNGStream: [Function: toFileStream],
  save: [Function: toFile],
  toDataURI: [Function: toDataURL] }
> 'teste'.bold()
TypeError: "teste".bold is not a function
    at repl:1:9
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:96:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:313:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:513:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)

I would like to know if is there any javascript method/property not supported

We already solve this by replacing .bold() by <b> </b> tag

Thanks!!
Renato

Problem with Windows

I think this is not working on a Windows OS right? the "qrcode.js" has the following lines of code

var QRCodeLib = require(__dirname+'/lib/qrcode-draw')
, terminalRender = require(__dirname+'/lib/termialrender.js')
, Canvas = require('canvas')
, fs = require('fs');

The delimter '/' is not always working on Windows, as I get the following error:

module.js:442 Uncaught Error: Cannot find module C:...\Documents\development\myProject/lib/qrcode-draw

Logos into generated QR codes

Hi,

Is there any plans of including support for embedding logos into the QR codes generated by the library? I'm talking about something like this:

http://www.visualead.com/blog/logo-qr-code/

Cheers

render SVG, renderToDataURL method.

exports.renderToDataURL = function renderToDataURL (qrData, options, cb) {
  if (typeof cb === 'undefined') {
    cb = options;
    options = undefined;
  }

  var svg = exports.render(qrData, options);
  svg = svg.replace(/[\n\r]+/g,'');

  var symbols = /[\r\n"%#()<>?\[\\\]^`{|}]/g;
  // Use single quotes instead of double to avoid encoding.
  if (svg.indexOf('"') >= 0) {
    svg = svg.replace(/"/g, "'");
  }

  svg = svg.replace(/>\s{1,}</g, "><");
  svg = svg.replace(/\s{2,}/g, " ");

  cb(null, 'data:image/svg+xml,' + svg.replace(symbols, escape));
}

Multiple QR Codes on one page

Hey,

Can somebody help me placing multiple (different) QR Codes on just one page. It doesn't seems to work here.

Thank you in advance,

Bas

build utf8 charset qrcode too short size

http://en.wikipedia.org/wiki/QR_code

qr_code support 2k size

but i use it

qrcode 你好啊 text.png.

Error: code length overflow. (84>72)
at Function.QRCode.createData (C:\Users\Administrator\AppData\Roaming\npm\no
de_modules\qrcode\lib\qrcode.js:325:9)
at Object.QRCode.makeImpl (C:\Users\Administrator\AppData\Roaming\npm\node_m
odules\qrcode\lib\qrcode.js:101:28)
at Object.QRCode.getBestMaskPattern (C:\Users\Administrator\AppData\Roaming
npm\node_modules\qrcode\lib\qrcode.js:135:9)
at Object.QRCode.make (C:\Users\Administrator\AppData\Roaming\npm\node_modul
es\qrcode\lib\qrcode.js:72:29)
at Object.QRCodeDraw.draw (C:\Users\Administrator\AppData\Roaming\npm\node_m
odules\qrcode\lib\qrcode-draw.js:95:10)
at exports.draw (C:\Users\Administrator\AppData\Roaming\npm\node_modules\qrc
ode\qrcode.js:70:15)
at Object.exports.save (C:\Users\Administrator\AppData\Roaming\npm\node_modu
les\qrcode\qrcode.js:130:2)

Draw QR in Internet Explorer (IE7)

Hi there,

Did anybody get this script working in Internet Explorer 7?

I did find the Google Excanvas javascript to make it possible showing/generating Canvas elements in Internet Explorer. For much QR drawing programs it works but not for this one; or does anybody else have the solution for me?

Thank you in advance,

Bas

install qrcode error

when i sudo npm install -g qrcode, it gives errors,

./util/has_cairo_freetype.sh: line 4: pkg-config: command not found

how can i solution it, thank you for your help!

Update pngjs dependency

Please, could you update your package.json dependencies for pngjs from 2.3.1 to latest 3.2.0 ?

toDataURL doesn't work in IE9

toDataURL doesn't work in IE9.
when I use it in IE9, the browser tell us that 'the object doesn't support “write”attributes or method'.Please check this problem.

update npm package

when user install qrcode with npm it's install an old version :\ can you update the npm package !

Regex string seems to be escaped incorrectly

The string used to construct RegExps from seems to contain incorrectly escaped unicode characters / invalid characters, making uglify break the code in our app.

var kanji = '(?:[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|' +

There should probably be double backslashes to actually pass the escaped unicode codes to the RegExp constructor.
Right now they turn into their actual characters before being consumed by the RegExp constructor:

$ node
> '[\u3000-\u303F]'
'[ -〿]'
>

So it's kind-of valid for uglify to resolve those escaped unicode chars in the string during build time what unfortunately results in a syntax error:

Uncaught SyntaxError: Invalid regular expression: /(?:[ -〿]|[�-ゟ]|[゠-ヿ]|[＀-￯]|[一-龯]|[★-☆]|[�-↕]|※|[�―‘’‥…“�∥≠]|[Α-ё]|[§¨±´×÷])+/: Range out of order in character class

Seems more like an escaping issue than an issue with uglify.

QR output to terminal can't be read by reader

Should I be expecting better (read, higher fidelity) output than this? QR code reader isn't able to read the output:

screen shot 2015-03-20 at 16 50 25

I can't tell if it's something related to my bash setup, or is this as expected?

not compiling with the latest node version (5.9.1)

npm install qrcode

> [email protected] install /Users/sagivo/dev/work/rbi/qr/node_modules/canvas
> node-gyp rebuild

Package xcb-shm was not found in the pkg-config search path.
Perhaps you should add the directory containing `xcb-shm.pc'
to the PKG_CONFIG_PATH environment variable
Package 'xcb-shm', required by 'cairo', not found
gyp: Call to './util/has_lib.sh freetype' returned exit status 0 while in binding.gyp. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/Users/sagivo/.nvm/versions/node/v5.9.1/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:305:16)
gyp ERR! stack     at emitTwo (events.js:100:13)
gyp ERR! stack     at ChildProcess.emit (events.js:185:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:204:12)
gyp ERR! System Darwin 15.4.0
gyp ERR! command "/Users/sagivo/.nvm/versions/node/v5.9.1/bin/node" "/Users/sagivo/.nvm/versions/node/v5.9.1/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/sagivo/dev/work/rbi/qr/node_modules/canvas
gyp ERR! node -v v5.9.1
gyp ERR! node-gyp -v v3.2.1
gyp ERR! not ok
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.
npm ERR! Darwin 15.4.0
npm ERR! argv "/Users/sagivo/.nvm/versions/node/v5.9.1/bin/node" "/Users/sagivo/.nvm/versions/node/v5.9.1/bin/npm" "install" "qrcode"
npm ERR! node v5.9.1
npm ERR! npm  v3.7.3
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the canvas package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs canvas
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls canvas
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/sagivo/dev/work/rbi/qr/npm-debug.log
sagiv:qr sagivo$

build failed

I got this npm, decided to use it. But when I install, it gives error

Can anyone please help me out ?

Error log

error

No license in repository

Hey, I know that the original JavaScript was licensed MIT, but I don't see an MIT license in/on/as part of your project.

Maybe just to help people who are really picky, do you think you could put an MIT license on this one too? :)

Adjust QRCode

Hi Soldair!

Can this module allow to adjust the square of qrcode. When the data is big the square look so small

qrcode

qrcode

Thankz,

unable to install with NPM

I'm getting the following error at install:

npm install qrcode
-
> [email protected] install /Users/me/myproject/node_modules/qrcode/node_modules/canvas
> node-gyp rebuild

./util/has_lib.sh: line 30: pkg-config: command not found
gyp: Call to './util/has_lib.sh freetype' returned exit status 0 while in binding.gyp. while trying to load binding.gyp
gyp ERR! configure error 
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:305:16)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 16.0.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/me/myproject/node_modules/qrcode/node_modules/canvas
gyp ERR! node -v v4.4.4
gyp ERR! node-gyp -v v3.3.1
gyp ERR! not ok 
npm ERR! Darwin 16.0.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "qrcode"
npm ERR! node v4.4.4
npm ERR! npm  v2.15.1
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the canvas package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs canvas
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! 
npm ERR!     npm owner ls canvas
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/me/myproject/npm-debug.log

I'm on OSX 10.12 (Sierra), Node 4.4.4, npm 2.15.1
any ideas?

options ignored

looks like the the functions QRCode.save, drawBitArray, and drawText still ignore options passed to them.

Dependecy problem

I am using qrcode with meteor. I added the dependency using meteorhacks:npm and when I tried to use the app, I saw this error:

Error: Module did not self-register.
    at Error (native)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/app/programs/server/npm/npm-container/node_modules/qrcode/node_modules/canvas/lib/bindings.js:3:18)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)

Could anybody has a clue about this issue?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.