### Install node-qrcode Locally
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Install the node-qrcode package as a project dependency.
```shell
npm install --save qrcode
```
--------------------------------
### Example Input Optimizations
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/encoding-modes.md
Provides examples of how different input strings are segmented into modes like alphanumeric, numeric, byte, and Kanji for QR code encoding.
```text
Input: "ISBN 1234567890"
→ Segments: ISBN (ALPHA), space (ALPHA), 1234567890 (NUMERIC)
Input: "Price: $99.99"
→ Segments: Price: (BYTE), space (BYTE), $ (ALPHA), 99.99 (NUMERIC)
Input: "こんにちは123"
→ Segments: こんにちは (KANJI with helper), 123 (NUMERIC)
```
--------------------------------
### Install qrcode CLI globally
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Install the qrcode package globally to use the 'qrcode' command from any terminal location. Alternatively, use 'npx' to run the command without global installation.
```bash
npm install -g qrcode
```
```bash
npx qrcode "your data here"
```
--------------------------------
### CLI Tool - Basic QR Code Generation
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/README.md
Demonstrates basic usage of the QR Code CLI tool for displaying QR codes in the terminal or saving them to files. Install globally using 'npm install -g qrcode'.
```bash
# Install globally
npm install -g qrcode
# Display in terminal
qrcode "Hello World"
# Save to file
qrcode -o qrcode.png "Hello World"
# SVG output
qrcode -t svg -o qrcode.svg "Hello World"
```
--------------------------------
### Install node-qrcode Globally
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Install the node-qrcode package globally using npm to make the 'qrcode' command available in your terminal.
```bash
npm install -g qrcode
```
--------------------------------
### Generate QR Code Buffer with Maximum Compression Options
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tobuffer.md
This example shows how to configure the renderer options for maximum compression when generating a QR code buffer, which can reduce file size.
```javascript
var QRCode = require('qrcode')
// Maximum compression
QRCode.toBuffer('Data', {
rendererOpts: {
deflateLevel: 9, // Highest compression
deflateStrategy: 3 // Optimal for PNG
}
}, function (err, buffer) {
if (err) throw err
console.log('Optimized size:', buffer.length)
})
```
--------------------------------
### Display Version Number
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Print the installed version number of the qrcode CLI tool. This is helpful for checking compatibility or reporting issues.
```bash
qrcode --version
```
--------------------------------
### Browser: Auto-Create Canvas with Callback
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tocanvas.md
This example demonstrates creating a QR code and automatically generating a new canvas element if none is provided. It uses a callback for handling the result.
```javascript
var QRCode = require('qrcode')
QRCode.toCanvas('Hello World', { scale: 8 }, function (err, canvas) {
if (err) throw err
document.body.appendChild(canvas)
})
```
--------------------------------
### Install Canvas Package for Node.js
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/README.md
Installs the 'canvas' package, which is required for HTML canvas rendering in Node.js environments.
```bash
npm install canvas
```
--------------------------------
### Generate QR Code Buffer and Encode to Base64
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tobuffer.md
This example demonstrates how to generate a QR code buffer and then convert it to a Base64 string, suitable for embedding in data URIs or other text-based formats.
```javascript
var QRCode = require('qrcode')
QRCode.toBuffer('Encoded Data', function (err, buffer) {
if (err) throw err
var base64 = buffer.toString('base64')
var dataUri = 'data:image/png;base64,' + base64
console.log(dataUri)
})
```
--------------------------------
### Generate QR Code with Kanji Mode and Helper
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
This example demonstrates how to generate a QR code with Kanji mode support by providing a custom `toSJISFunc`. This is necessary for encoding characters from the Shift JIS system efficiently.
```javascript
var QRCode = require('qrcode')
var toSJIS = require('qrcode/helper/to-sjis')
QRCode.toDataURL(kanjiString, { toSJISFunc: toSJIS }, function (err, url) {
console.log(url)
})
```
--------------------------------
### Handle Path Does Not Exist Error
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/errors.md
This example demonstrates how to handle 'ENOENT' errors, which occur when the target directory for a QR code file does not exist. It includes creating the directory if it's missing.
```javascript
QRCode.toFile('/nonexistent/dir/qrcode.png', 'data', cb)
```
```javascript
const path = require('path')
const fs = require('fs')
const dir = path.dirname('output/qrcode.png')
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
QRCode.toFile('output/qrcode.png', 'data', cb)
```
--------------------------------
### Full Error Message Structure Example
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/errors.md
Provides an example of the full error message structure when the chosen QR Code version is insufficient for the data and error correction level.
```text
The chosen QR Code version cannot contain this amount of data.
Minimum version required to store current data is: 3.
```
--------------------------------
### Generate QR Codes Using Promises
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tostring.md
This example shows how to use QRCode.toString() with Promises for asynchronous operations. It generates UTF-8, SVG, and terminal QR codes without explicit callbacks.
```javascript
import QRCode from 'qrcode'
async function generateQR() {
try {
const utf8 = await QRCode.toString('UTF8 QR')
const svg = await QRCode.toString('SVG QR', { type: 'svg' })
const term = await QRCode.toString('Terminal', { type: 'terminal' })
console.log(utf8)
return { utf8, svg, term }
} catch (err) {
console.error(err)
}
}
```
--------------------------------
### QR Code Numeric Mode Example
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/encoding-modes.md
Demonstrates how to generate a QR code using numeric mode. Supports automatic detection or manual specification of the 'numeric' mode for encoding decimal digits.
```javascript
const QRCode = require('qrcode')
// Automatic detection
QRCode.toFile('phone.png', '15551234567', cb)
// Manual mode
const segments = [
{ data: '15551234567', mode: 'numeric' }
]
QRCode.toFile('phone.png', segments, cb)
```
--------------------------------
### RGBA Hex Color Format Examples
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Illustrates the 8-digit RGBA hex format for specifying colors, including opaque, transparent, and semi-transparent values.
```bash
-d FF0000FF # Red, fully opaque
-l FFFFFF00 # White, fully transparent
-d 0000FF80 # Blue, 50% transparent
```
--------------------------------
### Buffering QR Code Stream with Through2
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tofilestream.md
This example uses the 'through2' library to create a transform stream for generating QR codes. It buffers the QR code data before passing it along the stream pipeline.
```javascript
const QRCode = require('qrcode')
const through = require('through2')
// Create a transform stream
const qrCodeGenerator = through.obj(function (data, enc, cb) {
var outStream = through()
QRCode.toFileStream(outStream, data.text, {
width: data.width || 200
})
outStream.on('data', (chunk) => {
this.push(chunk)
})
outStream.on('end', () => {
cb()
})
})
```
--------------------------------
### Node.js - Get QR Code as Buffer
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/README.md
Generate a QR code and receive it as a Buffer object, suitable for further processing or sending over a network. Requires the 'qrcode' module.
```javascript
const QRCode = require('qrcode')
QRCode.toBuffer('Hello World')
.then(buffer => console.log(buffer))
.catch(err => console.error(err))
```
--------------------------------
### Node.js - Save QR Code to File
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/README.md
Use this snippet to generate a QR code and save it directly to a PNG file. Ensure the 'qrcode' module is installed.
```javascript
const QRCode = require('qrcode')
QRCode.toFile('qrcode.png', 'Hello World', function (err) {
if (err) throw err
console.log('Done')
})
```
--------------------------------
### Server-Side (Node.js): Async/Await with Promises
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tocanvas.md
Demonstrates server-side QR code generation using async/await with Promises. This example generates a canvas with custom version, error correction, margin, and colors for a given URL.
```javascript
const QRCode = require('qrcode')
const { createCanvas } = require('canvas')
async function generateQR() {
const canvas = createCanvas(300, 300)
await QRCode.toCanvas(canvas, 'https://example.com', {
version: 5,
errorCorrectionLevel: 'H',
margin: 2,
color: {
dark: '#002D6B',
light: '#FFFFFF'
}
})
return canvas
}
```
--------------------------------
### Set QR Code Version
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Specify the QR code version for generation. The library automatically selects a suitable version if not provided. Version 2 is used in this example.
```javascript
QRCode.toDataURL('some text', { version: 2 }, function (err, url) {
console.log(url)
})
```
--------------------------------
### Handle Stream Write Errors Gracefully
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/errors.md
This example demonstrates the correct way to handle stream write errors for QR code generation. It sets up event listeners for both 'error' and 'finish' events on the stream.
```javascript
const fs = require('fs')
const QRCode = require('qrcode')
const stream = fs.createWriteStream('out.png')
QRCode.toFileStream(stream, 'data')
stream.on('error', function (err) {
console.error('Write failed:', err)
})
stream.on('finish', function () {
console.log('Write succeeded')
})
```
--------------------------------
### Basic Usage with Callback
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-todataurl.md
Encodes 'Hello World' into a QR code and appends it as an image to the document body. Requires the qrcode library to be imported.
```javascript
var QRCode = require('qrcode')
QRCode.toDataURL('Hello World', function (err, url) {
if (err) throw err
var img = document.createElement('img')
img.src = url
document.body.appendChild(img)
})
```
--------------------------------
### Display Help Message
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Show the help message for the qrcode CLI, listing all available commands and options. This is useful for quick reference.
```bash
qrcode -h
```
```bash
qrcode --help
```
--------------------------------
### SVG Structure Example
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tostring.md
This is an example of the structure of an SVG QR code string generated by the library. It includes the XML declaration, DOCTYPE, and SVG elements with path data.
```xml
```
--------------------------------
### QR Code Generation with Callbacks
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/README.md
Demonstrates how to generate a QR code to a file using the callback pattern. Ensure to handle potential errors in the callback function.
```javascript
// Callbacks
QRCode.toFile('out.png', 'data', (err) => {
if (err) console.error(err)
})
```
--------------------------------
### create(text, [options])
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Creates a QR code symbol. This is a reference to the create method documented elsewhere.
```APIDOC
## create(text, [options])
### Description
Creates a QR code symbol. Refer to the detailed documentation for the `create` method for usage and options.
### Parameters
#### Path Parameters
- **text** (String|Array) - Required - Text to encode or a list of objects describing segments.
- **options** (Object) - Optional - Configuration options for QR code generation. See [Options](#options).
```
--------------------------------
### Handle Invalid Arguments and Errors
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Example of an invalid QR code version resulting in an error message and a non-zero exit code.
```bash
$ qrcode -v 50 "data" # Invalid version
# Outputs error message to stderr, exits with code 1
```
--------------------------------
### Generate QR Code and Display in Browser
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/README.md
Shows how to generate a QR code and display it as an image in a web browser using a precompiled bundle. The QR code data is converted to a data URL.
```html
```
--------------------------------
### Get PNG Buffer (Node.js)
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/quick-reference.md
Generates a QR code and returns its PNG representation as a Buffer. Supports both callback and Promise-based approaches.
```javascript
const QRCode = require('qrcode')
QRCode.toBuffer('Hello World', function (err, buffer) {
if (err) throw err
// buffer contains PNG bytes
})
// With Promise
const buffer = await QRCode.toBuffer('Hello World')
```
--------------------------------
### Render QR Code to node-canvas (Node.js)
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/quick-reference.md
Renders a QR code directly onto a node-canvas object. Ensure the 'canvas' library is installed.
```javascript
const QRCode = require('qrcode')
const { createCanvas } = require('canvas')
const canvas = createCanvas(300, 300)
QRCode.toCanvas(canvas, 'Text', function (err) {
if (err) throw err
const png = canvas.toBuffer()
})
```
--------------------------------
### Get QR Code Data URI (Node.js)
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/quick-reference.md
Generates a QR code and returns it as a Data URI string, suitable for embedding in HTML or CSS.
```javascript
const QRCode = require('qrcode')
QRCode.toDataURL('Text', function (err, url) {
if (err) throw err
console.log(url) // data:image/png;base64,iVBOR...
})
```
--------------------------------
### Basic PNG Buffer Generation
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tobuffer.md
Generates a PNG image buffer from the text 'Hello World'. The callback function handles potential errors and logs the resulting buffer and its length.
```javascript
var QRCode = require('qrcode')
QRCode.toBuffer('Hello World', function (err, buffer) {
if (err) throw err
console.log(buffer) //
console.log(buffer.length) // e.g., 1024
})
```
--------------------------------
### QR Code Generation with Automatic Mode
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/encoding-modes.md
Demonstrates how to generate a QR code image file using the default automatic mode selection. It also shows how to inspect the optimized segments of a generated QR code object.
```javascript
const QRCode = require('qrcode')
// Automatic mode selection (default)
QRCode.toFile('mixed.png', 'ABCDE12345678?A1A', cb)
// Inspect segments in result
const qr = QRCode.create('ABCDE12345678?A1A')
console.log(qr.segments) // Shows optimized segments
```
--------------------------------
### QR Code Generation with Promises
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/README.md
Illustrates generating a QR code to a file using the Promise API. This approach allows for cleaner asynchronous error handling with try-catch blocks.
```javascript
// Promises
try {
await QRCode.toFile('out.png', 'data')
} catch (err) {
console.error(err)
}
```
--------------------------------
### Generate QR Code for Website Visitor Tracking
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Create a QR code containing a URL with query parameters for tracking website visitors.
```bash
qrcode "https://mysite.com/visitor?id=12345&session=abc"
```
--------------------------------
### Encoding Binary Data with Uint8Array
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/encoding-modes.md
Use byte mode with Uint8Array for encoding arbitrary binary data. This example demonstrates how to create QR code from binary data.
```javascript
const QRCode = require('qrcode')
// Binary data
const binaryData = new Uint8ClampedArray([253, 254, 255])
const segments = [
{ data: binaryData, mode: 'byte' }
]
QRCode.toFile('binary.png', segments, cb)
```
--------------------------------
### Generate QR Code to File (Node.js)
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/README.md
Demonstrates generating a QR code and saving it to a file using both callback and Promise styles in Node.js. Requires the 'qrcode' package.
```javascript
const QRCode = require('qrcode')
// Callback style
QRCode.toFile('out.png', 'data', cb)
// Promise style
await QRCode.toFile('out.png', 'data')
```
--------------------------------
### Server API: create()
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Creates a QR Code symbol and returns a qrcode object. This is the server-side equivalent of the browser's create function.
```APIDOC
## Server API: create()
### Description
Creates QR Code symbol and returns a qrcode object.
### Method Signature
`create(text, [options])`
### Parameters
#### `text`
Type: `String|Array`
Text to encode or a list of objects describing segments.
#### `options`
See [QR Code options](#qr-code-options).
### Returns
Type: `Object`
```javascript
// QRCode object
{
modules,
version,
errorCorrectionLevel,
maskPattern,
segments
}
```
```
--------------------------------
### Express.js Middleware for QR Code Generation
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tofilestream.md
Implement QR code generation as Express.js middleware. This example streams the QR code directly to the response object based on URL parameters.
```javascript
const QRCode = require('qrcode')
const express = require('express')
const app = express()
app.get('/qrcode/:data', (req, res) => {
res.setHeader('Content-Type', 'image/png')
res.setHeader('Cache-Control', 'public, max-age=3600')
QRCode.toFileStream(res, req.params.data, {
errorCorrectionLevel: 'H',
width: 250,
margin: 2
})
res.on('error', (err) => {
console.error('Response error:', err)
res.statusCode = 500
res.end('QR Code generation failed')
})
})
app.listen(3000)
```
--------------------------------
### Generate QR Code Buffer with Balanced Compression Options
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tobuffer.md
This snippet demonstrates generating a QR code buffer with balanced compression settings, offering a trade-off between file size and generation speed.
```javascript
var QRCode = require('qrcode')
// Faster compression
QRCode.toBuffer('Data', {
rendererOpts: {
deflateLevel: 6, // Balanced
deflateStrategy: 0 // Default
}
}, function (err, buffer) {
if (err) throw err
console.log('Balanced size:', buffer.length)
})
```
--------------------------------
### Avoiding 'Too few arguments provided' Error
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/errors.md
Shows correct argument usage for QRCode.toFileStream and QRCode.toFile to prevent the 'Too few arguments provided' error, highlighting required parameters for callback-style invocations.
```javascript
// toFileStream requires stream and text
const fs = require('fs')
const stream = fs.createWriteStream('out.png')
QRCode.toFileStream(stream, 'text') // ✓ Valid
QRCode.toFileStream(stream) // ✗ Error: too few args
// toFile requires path, text, and callback (or Promise support)
QRCode.toFile('out.png', 'text', cb) // ✓ Valid
QRCode.toFile('out.png', cb) // ✗ Error
```
--------------------------------
### Valid and Invalid QR Code Versions
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/errors.md
Illustrates the valid range of QR code versions (1-40) and examples of invalid version specifications. The version must be a number within the specified range.
```javascript
// Valid versions
{ version: 1 } // Minimum
{ version: 40 } // Maximum
{ version: 5 } // Any value in range
// Invalid versions
{ version: 0 } // Too low
{ version: 41 } // Too high
{ version: 'V5' } // Not a number
```
--------------------------------
### Write QR Code to HTTP Response Stream
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tofilestream.md
This example demonstrates streaming a QR code directly as an HTTP response. Set appropriate headers like 'Content-Type' and 'Content-Disposition' before calling toFileStream.
```javascript
const QRCode = require('qrcode')
const http = require('http')
const server = http.createServer((req, res) => {
if (req.url === '/qr') {
res.setHeader('Content-Type', 'image/png')
res.setHeader('Content-Disposition', 'attachment; filename="qrcode.png"')
QRCode.toFileStream(res, 'https://example.com', {
errorCorrectionLevel: 'H',
width: 200
})
res.on('error', (err) => {
console.error('Stream error:', err)
})
}
})
server.listen(3000)
```
--------------------------------
### Generate Product Catalog QR Code
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Generate a QR code for a product, including SKU, name, and price, formatted for easy parsing.
```bash
qrcode -o "catalog_SKU001.png" "SKU:001|Name:Product|Price:99.99"
```
--------------------------------
### Create QR Code and Save to File (Node.js)
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/quick-reference.md
Generates a QR code and saves it as a PNG file. Supports both callback and Promise-based approaches.
```javascript
const QRCode = require('qrcode')
QRCode.toFile('qrcode.png', 'Hello World', function (err) {
if (err) throw err
console.log('QR code saved')
})
// With Promise
await QRCode.toFile('qrcode.png', 'Hello World')
```
--------------------------------
### Generate SVG QR Code with Custom Colors
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tostring.md
This example demonstrates how to generate an SVG QR code with custom foreground and background colors. Specify colors using hex codes in the 'color' option.
```javascript
var QRCode = require('qrcode')
QRCode.toString('Colored SVG', {
type: 'svg',
width: 300,
margin: 2,
color: {
dark: '#0066CC',
light: '#FFFFFF'
}
}, function (err, svg) {
if (err) throw err
// Save SVG with custom colors
})
```
--------------------------------
### Pipe QR Code Stream through Compression
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tofilestream.md
This snippet shows how to generate a QR code, pipe it through a gzip compression stream, and save the compressed output. It includes cleanup of temporary files.
```javascript
var QRCode = require('qrcode')
var fs = require('fs')
var zlib = require('zlib')
// Create QR, compress, and save
var source = fs.createWriteStream('temp.png')
var gzip = zlib.createGzip()
var dest = fs.createWriteStream('qrcode.png.gz')
QRCode.toFileStream(source, 'Compressed Data', {
version: 3,
errorCorrectionLevel: 'M'
})
source.on('finish', function () {
// Compress after QR generation
fs.createReadStream('temp.png')
.pipe(gzip)
.pipe(dest)
.on('finish', function () {
console.log('Compressed and saved')
fs.unlinkSync('temp.png') // Clean up temp file
})
})
```
--------------------------------
### Node-QRCode File Organization
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/README.md
Illustrates the typical file structure generated by the node-qrcode project for its documentation.
```text
api-*.md # Individual API function references
configuration.md # All options and parameters
types.md # Data type definitions
encoding-modes.md # Encoding mode reference
errors.md # Error catalog
cli-reference.md # CLI tool documentation
quick-reference.md # Common tasks and patterns
advanced-techniques.md # Complex scenarios
modules-overview.md # Internal architecture
README.md # This file
```
--------------------------------
### Server API: toFile()
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Writes the QR Code to a file. Accepts the file path, text to encode, options, and a callback function for error handling.
```APIDOC
## Server API: toFile()
### Description
Writes QR Code to file.
### Method Signature
`toFile(filePath, text, [options], [cb(error)])`
### Parameters
#### `filePath`
Type: `String`
Path to save QR Code to.
#### `text`
Type: `String|Array`
Text to encode or a list of objects describing segments.
#### `options`
See [Options](#options).
#### `cb`
Type: `Function`
Callback function called on finish.
```
--------------------------------
### Convert QR Code to String
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Use toString() to get a string representation of the QR code. Supported output formats include terminal, utf8, and svg. A callback function handles the result or any errors.
```javascript
QRCode.toString('http://www.google.com', function (err, string) {
if (err) throw err
console.log(string)
})
```
--------------------------------
### Save QR Code as PNG
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Generates a QR code and saves it to a PNG file.
```bash
$ qrcode -o qrcode.png "https://example.com"
```
--------------------------------
### QR Code Alphanumeric Mode Example
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/encoding-modes.md
Illustrates generating a QR code with alphanumeric mode, which encodes uppercase letters, digits, and specific symbols. Shows both automatic detection (uppercase required) and manual mode specification.
```javascript
const QRCode = require('qrcode')
// Automatic detection (uppercase required)
QRCode.toFile('code.png', 'ORDER-12345', cb)
// Manual mode
const segments = [
{ data: 'ORDER-12345', mode: 'alphanumeric' }
]
QRCode.toFile('code.png', segments, cb)
// Won't auto-detect (has lowercase)
QRCode.toFile('code.png', 'Order-12345', cb) // Uses BYTE mode instead
```
--------------------------------
### Generate QR Code Buffer using Promises and Async/Await
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tobuffer.md
This snippet illustrates generating QR code buffers using both the Promise-based API and the async/await syntax for more modern JavaScript development.
```javascript
const QRCode = require('qrcode')
// Promise
QRCode.toBuffer('Promise QR')
.then(buffer => {
console.log('Buffer size:', buffer.length)
})
.catch(err => console.error(err))
// Async/Await
async function getQRBuffer() {
try {
const buffer = await QRCode.toBuffer('Async QR', {
errorCorrectionLevel: 'H'
})
return buffer
} catch (err) {
console.error(err)
}
}
```
--------------------------------
### Auto-Select QR Code Format by File Extension
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/advanced-techniques.md
This function automatically determines the QR code output format (PNG, JPEG, SVG, UTF-8) based on the file extension. It throws an error for unsupported formats. Ensure the 'qrcode' and 'path' modules are installed.
```javascript
const QRCode = require('qrcode')
const path = require('path')
async function smartSave(filepath, text, options = {}) {
const ext = path.extname(filepath).toLowerCase()
const formatMap = {
'.png': 'png',
'.jpg': 'image/jpeg',
'.svg': 'svg',
'.txt': 'utf8'
}
const type = formatMap[ext]
if (!type) {
throw new Error(`Unsupported format: ${ext}`)
}
await QRCode.toFile(filepath, text, {
...options,
type
})
}
// Usage
await smartSave('code.png', 'data') // PNG
await smartSave('code.svg', 'data') // SVG
await smartSave('code.txt', 'data') // UTF-8
```
--------------------------------
### Batch QR Code Generation with Promise.all
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/advanced-techniques.md
Generates multiple QR codes using native JavaScript Promises and `Promise.all`. This is an alternative to the 'batch' library for handling concurrent asynchronous tasks.
```javascript
// Or with Promise.all
const promises = items.map(item =>
QRCode.toFile(`qr_${item}.png`, item)
)
Promise.all(promises).then(() => console.log('Done'))
```
--------------------------------
### Client-Side QR Code Generation Example
Source: https://github.com/soldair/node-qrcode/blob/master/examples/clientside.html
This JavaScript code generates a QR code on an HTML canvas based on user inputs. It includes options for text, version, error correction level, margin, and colors. A debounce function is used to limit the rate at which the QR code is redrawn.
```javascript
var errorEl = document.getElementById('error')
var versionEl = document.getElementById('version')
var errorLevelEl = document.getElementById('errorLevel')
var modeEl = document.getElementById('mode')
var marginEl = document.getElementById('margin')
var lightColorEl = document.getElementById('lightColor')
var darkColorEl = document.getElementById('darkColor')
var canvasEl = document.getElementById('canvas')
var textEl = document.getElementById('input-text')
function debounce(func, wait, immediate) {
var timeout
return function() {
var context = this, args = arguments
var later = function() {
timeout = null
if (!immediate) func.apply(context, args)
}
var callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) func.apply(context, args)
}
}
function drawQR(text) {
errorEl.style.display = 'none'
canvasEl.style.display = 'block'
QRCode.toCanvas(canvasEl, text, {
version: versionEl.value,
errorCorrectionLevel: errorLevelEl.options[errorLevelEl.selectedIndex].text,
margin: marginEl.value,
color: {
light: lightColorEl.value,
dark: darkColorEl.value
},
toSJISFunc: QRCode.toSJIS
}, function (error, canvas) {
if (error) {
canvasEl.style.display = 'none'
errorEl.style.display = 'inline'
errorEl.textContent = error
}
})
}
var updateQR = debounce(function() {
var mode = modeEl.options[modeEl.selectedIndex].text
if (mode !== 'Auto') {
drawQR([{ data: textEl.value, mode: mode }])
} else {
drawQR(textEl.value)
}
}, 250)
versionEl.addEventListener('change', updateQR, false)
errorLevelEl.addEventListener('change', updateQR, false)
modeEl.addEventListener('change', updateQR, false)
marginEl.addEventListener('change', updateQR, false)
lightColorEl.addEventListener('change', updateQR, false)
darkColorEl.addEventListener('change', updateQR, false)
textEl.addEventListener('keyup', updateQR, false)
for (var i = 1; i <= 40; i++) {
versionEl.options[versionEl.options.length] = new Option(i.toString(), i)
}
drawQR(textEl.value)
```
--------------------------------
### Generate QR Code Buffer for HTTP Response
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tobuffer.md
This snippet shows how to create a QR code buffer and send it as an HTTP response. It handles potential errors during buffer generation and sets appropriate response headers.
```javascript
var QRCode = require('qrcode')
var http = require('http')
http.createServer(function (req, res) {
if (req.url === '/qr') {
QRCode.toBuffer(req.query.text || 'Default', {
width: 200
}, function (err, buffer) {
if (err) {
res.statusCode = 400
res.end('Error: ' + err.message)
return
}
res.setHeader('Content-Type', 'image/png')
res.setHeader('Content-Length', buffer.length)
res.end(buffer)
})
}
}).listen(3000)
```
--------------------------------
### Save QR Code to File
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Direct the QR code output to a file instead of displaying it in the terminal. The file format is automatically detected from the extension if not specified with --type.
```bash
qrcode -o qrcode.png "data"
```
```bash
qrcode -o qrcode.svg "data"
```
```bash
qrcode -o qrcode.txt "data"
```
--------------------------------
### Write PNG Buffer to File
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tobuffer.md
Generates a PNG image buffer from the text 'PNG Data' with a specified width and writes the buffer to a file named 'qrcode.png'. It logs the number of bytes saved.
```javascript
var QRCode = require('qrcode')
var fs = require('fs')
QRCode.toBuffer('PNG Data', { width: 300 }, function (err, buffer) {
if (err) throw err
fs.writeFileSync('qrcode.png', buffer)
console.log('Saved', buffer.length, 'bytes')
})
```
--------------------------------
### Usage of toSJIS Helper Function
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/modules-overview.md
Demonstrates how to use the `toSJIS` helper function for Kanji string conversion when creating a QR code. This is useful in environments where SJIS encoding is required and the default Kanji mode needs to be overridden.
```javascript
const toSJIS = require('qrcode/helper/to-sjis')
QRCode.create(kanjiStr, { toSJISFunc: toSJIS })
```
--------------------------------
### Pipe QR Code Data to Another Program
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Redirect QR code data to standard output and pipe it to other commands like ImageMagick or wc.
```bash
# Display with ImageMagick
qrcode "data" | display -
```
```bash
# Get file size
qrcode -o - "data" | wc -c
```
--------------------------------
### Basic QRCode.create() Usage
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-create.md
Use this snippet to create a basic QR Code symbol object from a string. It automatically determines the QR Code version and other settings.
```javascript
const QRCode = require('qrcode')
const qrData = QRCode.create('Hello World')
console.log(qrData.version) // e.g., 1
console.log(qrData.modules.size) // e.g., 21 (depends on version)
```
--------------------------------
### Using Promises
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-todataurl.md
Encodes contact information into a QR code using Promises. If successful, it creates a download link for the QR code image; otherwise, it logs the error.
```javascript
import QRCode from 'qrcode'
QRCode.toDataURL('Contact: john@example.com')
.then(url => {
const link = document.createElement('a')
link.href = url
link.download = 'qrcode.png'
link.click()
})
.catch(err => console.error(err))
```
--------------------------------
### Generate Multiple QR Codes in a Batch
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Use a bash loop to generate a series of QR codes, each with a unique identifier and content.
```bash
#!/bin/bash
for i in {1..10}; do
qrcode -o "qr_$i.png" "Item $i"
done
```
--------------------------------
### Asynchronous QR Code File Saving with Promises
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tofile.md
Saves a QR code to a file using async/await syntax with Promises. Includes error handling via a try-catch block.
```javascript
const QRCode = require('qrcode')
async function saveQR() {
try {
await QRCode.toFile('qrcode.png', 'Async/Await', {
errorCorrectionLevel: 'H',
width: 300
})
console.log('File saved successfully')
} catch (err) {
console.error('Save failed:', err)
}
}
saveQR()
```
--------------------------------
### toFile(path, text, [options], [cb(error)])
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Saves the QR Code to an image file.
```APIDOC
## toFile(path, text, [options], [cb(error)])
### Description
Saves the QR Code to an image file. The format is guessed from the file extension if `options.type` is not specified. Recognized extensions are `png`, `svg`, `txt`.
### Parameters
#### Path Parameters
- **path** (String) - Required - Path where to save the file.
- **text** (String|Array) - Required - Text to encode or a list of objects describing segments.
- **options** (Object) - Optional - Configuration options.
- **type** (String) - Optional - Output format. Possible values: `png`, `svg`, `utf8`. Defaults to `png`.
- **rendererOpts.deflateLevel** (Number) - Optional (png only) - Compression level for deflate. Defaults to `9`.
- **rendererOpts.deflateStrategy** (Number) - Optional (png only) - Compression strategy for deflate. Defaults to `3`.
- **cb** (Function) - Required - Callback function called on finish. It receives an error argument if an error occurred.
### Request Example
```javascript
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')
})
```
```
--------------------------------
### Basic PNG File Generation
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tofile.md
Generates a QR code and saves it as a PNG file. A callback function is used to handle potential errors.
```javascript
var QRCode = require('qrcode')
QRCode.toFile('qrcode.png', 'Hello World', function (err) {
if (err) throw err
console.log('QR code saved to qrcode.png')
})
```
--------------------------------
### Generate QR Code with Timestamp
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Create a QR code that includes a timestamp in its filename and content, useful for time-sensitive data.
```bash
timestamp=$(date +%s)
qrcode -o "qr_$timestamp.png" "Generated at $timestamp"
```
--------------------------------
### Auto-Detection of Output Format by File Extension
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Demonstrates how the CLI automatically detects the output format (PNG, SVG, UTF-8 text) based on the file extension when `--type` is not specified.
```bash
qrcode -o code.png "auto-detected as PNG"
qrcode -o code.svg "auto-detected as SVG"
qrcode -o code.txt "auto-detected as UTF-8"
```
--------------------------------
### Specify Output Format
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Choose the output format for the QR code. Supported formats include PNG (default), SVG, and UTF-8 text for terminal display.
```bash
qrcode -t png "data" # PNG (default)
```
```bash
qrcode -t svg "data" # SVG
```
```bash
qrcode -t utf8 "data" # UTF-8 text
```
--------------------------------
### Kanji Mode QR Code Generation with Helper
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/encoding-modes.md
Shows how to encode Japanese characters using Kanji mode, which requires a specific helper function for Shift JIS conversion. It also illustrates the fallback to byte mode if the helper is not provided.
```javascript
const QRCode = require('qrcode')
const toSJIS = require('qrcode/helper/to-sjis')
QRCode.toFile('kanji.png', 'こんにちは', {
toSJISFunc: toSJIS
}, cb)
```
```javascript
const QRCode = require('qrcode')
const toSJIS = require('qrcode/helper/to-sjis')
// Japanese text
QRCode.toDataURL('日本語テキスト', {
errorCorrectionLevel: 'H',
toSJISFunc: toSJIS
})
.then(url => console.log(url))
.catch(err => console.error(err))
// Without toSJISFunc, falls back to byte mode
QRCode.toDataURL('日本語テキスト') // Uses BYTE mode
```
--------------------------------
### Configure QR Code Scaling and Width
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/configuration.md
Control the output size of QR codes using either 'scale' for pixels per module or 'width' for a fixed output dimension. The 'width' option takes precedence.
```javascript
{ scale: 4 }
```
```javascript
{ width: 300 }
```
--------------------------------
### QRCode.create() with Custom Options
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-create.md
Create a QR Code symbol object with specific configuration options like version, error correction level, and mask pattern. This allows for fine-grained control over the QR Code's properties.
```javascript
const QRCode = require('qrcode')
const qrData = QRCode.create('https://example.com', {
version: 5,
errorCorrectionLevel: 'H',
maskPattern: 3
})
```
--------------------------------
### Specify QR Code Version
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Set a specific QR Code version (1-40) for generation. This allows control over the size and data capacity of the QR code.
```bash
qrcode -v 5 "data"
```
--------------------------------
### Server API: toString()
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Returns a string representation of the QR Code. This is the server-side version, supporting output formats like terminal, utf8, and SVG.
```APIDOC
## Server API: toString()
### Description
Returns a string representation of the QR Code.
### Method Signature
`toString(text, [options], [cb(error, string)])`
### Parameters
#### `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](#options) for other settings.
#### `cb`
Type: `Function`
Callback function called on finish.
```
--------------------------------
### toString(text, [options], [cb(error, string)])
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Returns a string representation of the QR Code, potentially as SVG.
```APIDOC
## toString(text, [options], [cb(error, string)])
### Description
Returns a string representation of the QR Code. If the output format is `svg`, it returns a string containing XML code.
### Parameters
#### Path Parameters
- **text** (String|Array) - Required - Text to encode or a list of objects describing segments.
- **options** (Object) - Optional - Configuration options.
- **type** (String) - Optional - Output format. Possible values: `utf8`, `svg`, `terminal`. Defaults to `utf8`.
- **cb** (Function) - Required - Callback function called on finish. It receives an error and the string argument.
### Request Example
```javascript
QRCode.toString('http://www.google.com', function (err, string) {
if (err) throw err
console.log(string)
})
```
```
--------------------------------
### Generate QR Code from Plain Text
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/cli-reference.md
Encode simple plain text strings into QR codes using the basic command.
```bash
qrcode "Hello World"
```
--------------------------------
### ES6/ES7 QR Code Generation with Promises and Async/Await
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Utilize Promises and Async/Await for asynchronous QR code generation in modern JavaScript environments. This approach simplifies error handling and asynchronous flow compared to traditional callbacks.
```javascript
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)
}
}
```
--------------------------------
### Server API: toFileStream()
Source: https://github.com/soldair/node-qrcode/blob/master/README.md
Returns a stream of the QR Code image. Accepts the stream, text to encode, and options.
```APIDOC
## Server API: toFileStream()
### Description
Returns a stream of the QR Code image.
### Method Signature
`toFileStream(stream, text, [options])`
### Parameters
#### `stream`
Type: `Stream`
Stream where to write QR Code to.
#### `text`
Type: `String|Array`
Text to encode or a list of objects describing segments.
#### `options`
See [Options](#options).
```
--------------------------------
### Server-Side PNG to Buffer Conversion
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-todataurl.md
Demonstrates how to obtain a PNG data URI and then convert it into a Buffer on the server-side. This is useful when a raw byte buffer is needed instead of a base64 string.
```javascript
const QRCode = require('qrcode')
QRCode.toDataURL('Important: use toBuffer() for true PNG buffer', {
type: 'image/png'
}, function (err, url) {
if (err) throw err
// url is base64 string, use toBuffer() for actual bytes
const base64Data = url.replace(/^data:image\/png;base64,/, '')
const buffer = Buffer.from(base64Data, 'base64')
})
```
--------------------------------
### Generate Basic Text QR Code as Data URL
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/configuration.md
Generates a QR code for 'Hello World' with medium error correction, a margin of 4, and a scale of 4. Use this for standard QR code generation.
```javascript
QRCode.toDataURL('Hello World', {
errorCorrectionLevel: 'M',
margin: 4,
scale: 4
})
```
--------------------------------
### PNG File Generation with Compression Settings
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/api-tofile.md
Saves a QR code as a PNG file, specifying custom deflate compression level and strategy for optimization.
```javascript
var QRCode = require('qrcode')
QRCode.toFile('compressed.png', 'Data', {
rendererOpts: {
deflateLevel: 9, // Maximum compression
deflateStrategy: 3 // Optimal for PNG
}
}, function (err) {
if (err) throw err
})
```
--------------------------------
### Generate QR Code with Maximum PNG Compression
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/configuration.md
Generates a QR code for 'Data' using the maximum PNG compression levels for both deflate level and strategy. This optimizes file size at the cost of generation time.
```javascript
QRCode.toBuffer('Data', {
rendererOpts: {
deflateLevel: 9, // Maximum compression
deflateStrategy: 3 // Optimal for PNG
}
})
```
--------------------------------
### Catching 'No input text' Error
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/errors.md
Demonstrates how to catch the 'No input text' error when an empty string is provided as input to QRCode.create, toDataURL (callback and Promise versions).
```javascript
const QRCode = require('qrcode')
try {
QRCode.create('') // Throws error
} catch (err) {
console.error(err.message) // "No input text"
}
// With callbacks
QRCode.toDataURL('', function (err, url) {
if (err) console.error(err.message)
})
// With promises
QRCode.toDataURL('')
.catch(err => console.error(err.message))
```
--------------------------------
### Encode Binary Data to QR Code
Source: https://github.com/soldair/node-qrcode/blob/master/_autodocs/advanced-techniques.md
Reads a file, encodes its content as a base64 string, and generates a QR code. Handles large files by splitting the base64 string into chunks if necessary.
```javascript
const QRCode = require('qrcode')
const fs = require('fs')
// Read file and encode as base64
const fileData = fs.readFileSync('image.jpg')
const base64 = fileData.toString('base64')
// Split if needed for size
const maxSize = 1000
if (base64.length > maxSize) {
const chunks = base64.match(new RegExp('.{1,' + maxSize + '}', 'g'))
chunks.forEach((chunk, i) => {
QRCode.toFile(`qr_${i}.png`, chunk, cb)
})
} else {
QRCode.toFile('data.png', base64, cb)
}
```