ZXing-C++ WebAssembly as an ES/CJS module with types. Read or write barcodes in various JS runtimes: Web, Node.js, Bun, and Deno.
git clone --recurse-submodules https://github.com/Sec-ant/zxing-wasm
cd zxing-wasm
# Install pnpm before executing the next command:
# https://pnpm.io/installation
pnpm i --frozen-lockfile
# Install CMake before executing the next command:
# https://cmake.org/download/
pnpm cmake
# Install Emscripten before executing the next command:
# https://emscripten.org/docs/getting_started/downloads.html
pnpm build:wasm
pnpm build
npm i zxing-wasm
This package exports three subpaths: full
, reader
, and writer
. You can choose the one that fits your needs. If you use TypeScript, you should set moduleResolution
to bundler
, node16
, or nodenext
in your tsconfig.json
file to properly resolve the exported module.
zxing-wasm
or zxing-wasm/full
These two subpaths provide functions to read and write barcodes. The wasm binary size is ~1.30 MB.
import { readBarcodes, writeBarcode } from "zxing-wasm";
or
import { readBarcodes, writeBarcode } from "zxing-wasm/full";
zxing-wasm/reader
This subpath only provides a function to read barcodes. The wasm binary size is ~906 KB.
import { readBarcodes } from "zxing-wasm/reader";
zxing-wasm/writer
This subpath only provides a function to write barcodes. The wasm binary size is ~1.17 MB.
import { writeBarcode } from "zxing-wasm/writer";
Apart from ES and CJS modules, this package also ships IIFE scripts. The registered global variable is named ZXingWASM
, where you can access all the exported functions and variables under it.
Replace the <version>
with the desired version number.
<!-- full -->
<script src="https://cdn.jsdelivr.net/npm/zxing-wasm@<version>/dist/iife/full/index.js"></script>
<!-- reader -->
<script src="https://cdn.jsdelivr.net/npm/zxing-wasm@<version>/dist/iife/reader/index.js"></script>
<!-- writer -->
<script src="https://cdn.jsdelivr.net/npm/zxing-wasm@<version>/dist/iife/writer/index.js"></script>
readBarcodes
readBarcodes
accepts an image Blob
, image File
, or an ImageData
as its first argument, and various options are supported in ReaderOptions
as an optional second argument.
The return result of this function is a Promise
of an array of ReadResult
s.
e.g.
import { readBarcodes, type ReaderOptions } from "zxing-wasm/reader";
const readerOptions: ReaderOptions = {
tryHarder: true,
formats: ["QRCode"],
maxNumberOfSymbols: 1,
};
/**
* Read from image file/blob
*/
const imageFile = await fetch(
"https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=Hello%20world!",
).then((resp) => resp.blob());
const imageFileReadResults = await readBarcodes(imageFile, readerOptions);
console.log(imageFileReadResults[0].text); // Hello world!
/**
* Read from image data
*/
const imageData = await createImageBitmap(imageFile).then((imageBitmap) => {
const { width, height } = imageBitmap;
const context = new OffscreenCanvas(width, height).getContext(
"2d",
) as OffscreenCanvasRenderingContext2D;
context.drawImage(imageBitmap, 0, 0, width, height);
return context.getImageData(0, 0, width, height);
});
const imageDataReadResults = await readBarcodes(imageData, readerOptions);
console.log(imageDataReadResults[0].text); // Hello world!
writeBarcode
The first argument of writeBarcode
is a text string or an Uint8Array
of bytes to be encoded, and the optional second argument WriterOptions
accepts several writer options.
The return result of this function is a Promise
of a WriteResult
.
e.g.
import { writeBarcode, type WriterOptions } from "zxing-wasm/writer";
const writerOptions: WriterOptions = {
format: "QRCode",
scale: 3,
};
const writeOutput = await writeBarcode("Hello world!", writerOptions);
console.log(writeOutput.svg); // An SVG string.
console.log(writeOutput.utf8); // A multi-line string made up of " ", "▀", "▄", "█" characters.
console.log(writeOutput.image); // A PNG image blob.
.wasm
ServingWhen using this package, a .wasm
binary file needs to be served somewhere so the runtime can fetch, compile and instantiate the WASM module. In order to provide a smooth development experience, the serve path is automatically assigned a jsDelivr CDN url upon build.
If you want to change the serve path to your own server or other CDNs, please use prepareZXingModule
and pass an overrides
object with a custom defined locateFile
function before reading or writing barcodes. locateFile
is one of the Emscripten Module
attribute hooks that can affect the code execution of the Module
object during its lifecycle.
e.g.
import { prepareZXingModule, writeBarcode } from "zxing-wasm";
// Override the locateFile function
prepareZXingModule({
overrides: {
locateFile: (path, prefix) => {
if (path.endsWith(".wasm")) {
return `https://unpkg.com/zxing-wasm@2/dist/full/${path}`;
}
return prefix + path;
},
},
});
// Call read or write functions afterward
const writeOutput = await writeBarcode("Hello world!");
If you want to use this library in non-web runtimes (such as Node.js, Bun, Deno, etc.) without setting up a server, there are several possible approaches. Because API support can differ between runtime environments and versions, you may need to adapt these examples or choose alternative methods depending on your specific runtime’s capabilities. Below are some example configurations for Node.js.
Use the Module.instantiateWasm
API
import { readFileSync } from "node:fs";
import { prepareZXingModule } from "zxing-wasm/reader";
const wasmFileBuffer = readFileSync("/path/to/the/zxing_reader.wasm");
prepareZXingModule({
overrides: {
instantiateWasm(imports, successCallback) {
WebAssembly.instantiate(wasmFileBuffer, imports).then(({ instance }) =>
successCallback(instance),
);
return {};
},
},
});
Use the Module.wasmBinary
API
import { readFileSync } from "node:fs";
import { prepareZXingModule } from "zxing-wasm/reader";
prepareZXingModule({
overrides: {
wasmBinary: readFileSync("/path/to/the/zxing_reader.wasm")
.buffer as ArrayBuffer,
},
});
Use the Module.locateFile
API with an Object URL
import { readFileSync } from "node:fs";
import { prepareZXingModule } from "zxing-wasm/reader";
// Create an Object URL for the .wasm file.
const wasmFileUrl = URL.createObjectURL(
new Blob([readFileSync("/path/to/the/zxing_reader.wasm")], {
type: "application/wasm",
}),
);
prepareZXingModule({
overrides: {
locateFile: (path, prefix) => {
if (path.endsWith(".wasm")) {
return wasmFileUrl;
}
return prefix + path;
},
// Call `URL.revokeObjectURL(wasmFileUrl)` after the ZXing module
// is fully instantiated to free up memory.
postRun: [
() => {
URL.revokeObjectURL(wasmFileUrl);
},
],
},
});
Use the Module.locateFile
API with a Base64-encoded Data URL (Not recommended)
import { readFileSync } from "node:fs";
import { prepareZXingModule } from "zxing-wasm/reader";
const wasmBase64 = readFileSync("/path/to/the/zxing_reader.wasm").toString(
"base64",
);
const wasmUrl = `data:application/wasm;base64,${wasmBase64}`;
prepareZXingModule({
overrides: {
locateFile: (path, prefix) => {
if (path.endsWith(".wasm")) {
return `data:application/wasm;base64,${readFileSync(
"/path/to/the/zxing_reader.wasm",
).toString("base64")}`;
}
return prefix + path;
},
},
});
Each version of this library has a unique corresponding .wasm
file. If you choose to serve it yourself, please ensure that the .wasm
file matches the version of the zxing-wasm
library you are using. Otherwise you may encounter unexpected errors.
For convenience, this library provides an exported ZXING_WASM_VERSION
variable to indicate the resolved version of the zxing-wasm
you are using:
import { ZXING_WASM_VERSION } from "zxing-wasm";
The SHA-256 hash of the .wasm
file (in hex format) is also exported as ZXING_WASM_SHA256
, in case you want to make sure you are serving the exactly same file:
import { ZXING_WASM_SHA256 } from "zxing-wasm";
To acquire the .wasm
files for customized serving, in addition to finding them by searching in your node_modules
folder, they can also be downloaded from CDNs like jsDelivr:
zxing_full.wasm
:
https://cdn.jsdelivr.net/npm/zxing-wasm@<version>/dist/full/zxing_full.wasm
zxing_reader.wasm
:
https://cdn.jsdelivr.net/npm/zxing-wasm@<version>/dist/reader/zxing_reader.wasm
zxing_writer.wasm
:
https://cdn.jsdelivr.net/npm/zxing-wasm@<version>/dist/writer/zxing_writer.wasm
.wasm
Instantiation Timing and CachingBy default, the .wasm
binary will not be fetched and instantiated until a readBarcodes
or writeBarcode
function is called. This behavior avoids unnecessary network requests and instantiation overhead if you decide to override the default .wasm
serving path or other settings before using the library. Calling prepareZXingModule
with overrides
alone does not change this default behavior:
prepareZXingModule({
overrides: {
/* ... your desired overrides ... */
},
}); // <-- returns void
However, if you want to explicitly trigger the download and instantiation of the .wasm
binary, you can set the fireImmediately
option to true
. Doing so also causes prepareZXingModule
to return a Promise
that resolves to the underlying Emscripten module. This allows you to await
the instantiation process:
prepareZXingModule({
overrides: {
/* ... your desired overrides ... */
},
fireImmediately: true,
}); // <-- returns Promise<ZXingModule>
Because different overrides
settings can influence how this library locates and instantiates the .wasm
binary, the library performs an equality check on overrides
to determine if the .wasm
binary should be re-fetched and re-instantiated. By default, it is determined by a shallow comparison of the overrides
object. If you prefer a different method of comparison, you can supply a custom equalityFn
:
prepareZXingModule({
overrides: {
/* ... your desired overrides ... */
},
fireImmediately: true,
equalityFn: () => false, // <-- force re-fetch and re-instantiate
});
MIT