Security News
NIST Misses 2024 Deadline to Clear NVD Backlog
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
QRCode / 2d Barcode api with both server side and client side support using canvas
The qrcode npm package is a library for generating QR codes. It can be used to create QR codes in various formats such as images or canvas for web applications, and it supports a range of customization options.
Generating QR Code as Data URL
This feature allows you to generate a QR code as a data URL, which can be used directly in image tags or CSS backgrounds.
const QRCode = require('qrcode');
QRCode.toDataURL('https://www.example.com', function (err, url) {
console.log(url);
});
Generating QR Code as PNG Image File
This feature allows you to generate a QR code and save it as a PNG image file on the filesystem.
const QRCode = require('qrcode');
QRCode.toFile('path/to/output.png', 'https://www.example.com', function (err) {
if (err) throw err;
console.log('QR Code saved as image file!');
});
Generating QR Code as UTF8 String
This feature allows you to generate a QR code as a UTF8 string, which can be printed to the terminal or used in text-based formats.
const QRCode = require('qrcode');
QRCode.toString('https://www.example.com', { type: 'terminal' }, function (err, string) {
if (err) throw err;
console.log(string);
});
The qrcode-svg package generates QR codes in SVG format. It offers a different output format compared to qrcode and might be preferred when working with vector graphics.
The qr-image package is another alternative for generating QR codes. It can create QR codes in PNG, SVG, EPS, and PDF formats. It provides a different API and additional output formats compared to qrcode.
QR code/2d barcode generator.
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
node-canvas
is required.
(note: this dependency is only needed for server side use and will be likely removed in the future)
node-canvas
is a native module and requires dev packages of Cairo
and Pango
to compile.
Make sure to have these libs available on your system before run npm install qrcode
Installation instructions are available on node-canvas page.
qrcode <text> [output file]
Output image format is detected from file extension.
Only png
and svg
format are supported for now.
If no output file is specified, the QR Code will be rendered directly in the terminal.
qrcode "Draw a QR Code in my terminal"
qrcode "I like to save qrs as a PNG" qr.png
qrcode "I also like to save them as a SVG" qr.svg
node-qrcode
can be used in browser through module bundlers like Browserify and Webpack or by including the precompiled bundle present in build/
folder.
<!-- index.html -->
<html>
<body>
<canvas id="canvas"></canvas>
<script src="bundle.js"></script>
</body>
</html>
// index.js -> bundle.js
var QRCode = require('qrcode')
var QRCodeDraw = new QRCode.QRCodeDraw()
var canvas = document.getElementById('canvas')
QRCodeDraw.draw(canvas, 'sample text', function (error, canvas) {
if (error) console.error(error)
console.log('success!');
})
<canvas id="canvas"></canvas>
<script src="/build/qrcode.min.js"></script>
<script>
var qrcodedraw = new qrcodelib.qrcodedraw()
qrcodedraw.draw(document.getElementById('canvas'), 'sample text', function (error, canvas) {
if (error) console.error(error)
console.log('success!');
})
</script>
Precompiled files are generated in build/
folder during installation.
To manually rebuild the lib run:
npm run build
Simply require the module qrcode
var QRCode = require('qrcode')
QRCode.toDataURL('I am a pony!', function (err, url) {
console.log(url)
})
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)
})
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)
})
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 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.
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.
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)
})
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>
var qrcodedraw = new qrcodelib.qrcodedraw()
qrcodedraw.draw(document.getElementById('canvas'),
'sample text', { toSJISFunc: qrcodelib.toSJIS }, function (error, canvas) {
if (error) console.error(error)
console.log('success!');
})
</script>
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.
Draws qr code symbol to canvas
Type: DOMElement
Canvas where to draw QR Code
Type: String|Array
Text to encode or a list of objects describing segments
Type: Number
QR Code version. If not specified the more suitable value will be calculated.
Type: String
Default: M
Error correction level.
Possible values are low, medium, quartile, high
or L, M, Q, H
.
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.
Type: Function
Callback function called on finish
Draws qr code symbol to canvas Returns a node canvas object. See https://github.com/Automattic/node-canvas
Returns mime image/png data url for the 2d barcode.
SVG output!
Saves png to the path specified returns bytes written.
Returns an ascii representation of the qrcode using unicode characters and ansi control codes for background control.
Returns an array with each value being either 0 light or 1 dark and the width of each row. This is enough info to render a qrcode any way you want. =)
Type: String|Array
Text to encode or a list of objects describing segments
Type: Number
QR Code version. If not specified the more suitable value will be calculated.
Type: String
Default: M
Error correction level.
Possible values are low, medium, quartile, high
or L, M, Q, H
.
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.
Type: Function
Callback function called on finish
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
This lib is based on "QRCode for JavaScript" which Kazuhiko Arase thankfully MIT licensed.
The word "QR Code" is registered trademark of:
DENSO WAVE INCORPORATED
FAQs
QRCode / 2d Barcode api with both server side and client side support using canvas
The npm package qrcode receives a total of 2,314,278 weekly downloads. As such, qrcode popularity was classified as popular.
We found that qrcode demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.