search
HomeWeb Front-endJS TutorialDetailed explanation of Node.js barcode recognition program construction ideas

In this article, we will show a very simple method to build a custom Node module, which encapsulates Dynamsoft Barcode Reader SDK, supports Windows, Linux and OS X, and we will demonstrate how to integrate this The module implements an online barcode reading application.

More and more web developers are choosing Node to build websites because it is becoming more and more convenient to use JavaScript to develop complex server-side web applications. In order to extend the functionality of Node on different platforms, Node allows developers to create extensions using C/C++.

Introduction

Dynamsoft Barcode Reader provides a C/C++ shared library for barcode parsing for Windows, Linux and OS X. Its biggest advantage is that it is suitable for a variety of high-level programming languages, including JavaScript, Python, Java, Ruby, PHP, etc., as long as the C/C++ API can be encapsulated as an extension, it can be used. Regardless of the programming language, it only takes a few lines of code to parse the barcode.

Support 1D/2D barcode types

Code 39, Code 93, Code 128, Codabar, Interleaved 2 of 5, EAN-8, EAN-13, UPC- A, UPC-E,Industrial 2 of 5
QRCode
DataMatrix
PDF417

Supported image types

BMP, JPEG, PNG, GIF , TIFF, PDF

Runtime environment

Windows, Linux & Mac
Node v5.5.0

Node.js barcode extension

Node.js extends dynamically linked shared objects written in C/C++. If you have not been exposed to this technology, you can read the official tutorial.

Create an extension

Create a file named dbr.cc and add the method DecodeFile:

#include#include#include "If_DBR.h"
#include "BarcodeFormat.h"
#include "BarcodeStructs.h"
#include "ErrorCode.h"
using namespace v8;
void DecodeFile(const FunctionCallbackInfo& args) {
}
void Init(Handleexports) {
NODE_SET_METHOD(exports, "decodeFile", DecodeFile);
}
NODE_MODULE(dbr, Init)

Parse Parameters passed from JavaScript

Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
String::Utf8Value license(args[0]->ToString());
String::Utf8Value fileName(args[1]->ToString());
char *pFileName = *fileName;
char *pszLicense = *license;
__int64 llFormat = args[2]->IntegerValue();
Localcb = Local::Cast(args[3]);

Parse the barcode image:

int iMaxCount = 0x7FFFFFFF;
ReaderOptions ro = {0};
pBarcodeResultArray pResults = NULL;
ro.llBarcodeFormat = llFormat;
ro.iMaxBarcodesNumPerPage = iMaxCount;
DBR_InitLicense(pszLicense);
// Decode barcode image
int ret = DBR_DecodeFile(pFileName, &ro, &pResults);

will Convert barcode to string:

const char * GetFormatStr(__int64 format)
{
if (format == CODE_39)
return "CODE_39";
if (format == CODE_128)
return "CODE_128";
if (format == CODE_93)
return "CODE_93";
if (format == CODABAR)
return "CODABAR";
if (format == ITF)
return "ITF";
if (format == UPC_A)
return "UPC_A";
if (format == UPC_E)
return "UPC_E";
if (format == EAN_13)
return "EAN_13";
if (format == EAN_8)
return "EAN_8";
if (format == INDUSTRIAL_25)
return "INDUSTRIAL_25";
if (format == QR_CODE)
return "QR_CODE";
if (format == PDF417)
return "PDF417";
if (format == DATAMATRIX)
return "DATAMATRIX";

return "UNKNOWN";
}

Convert the result to v8 object:

LocalbarcodeResults = Array::New(isolate);
for (int i = 0; i < count; i++)
{
tmp = ppBarcodes[i];
Localresult = Object::New(isolate);
result->Set(String::NewFromUtf8(isolate, "format"), String::NewFromUtf8(isolate, GetFormatStr(tmp->llFormat)));
result->Set(String::NewFromUtf8(isolate, "value"), String::NewFromUtf8(isolate, tmp->pBarcodeData));
barcodeResults->Set(Number::New(isolate, i), result);
}

Build Extension

Requirements:

Windows: Requires DBR for Windows, visual Studio, and Python v2.7 to be installed.

Linux: Install DBR for Linux.

Mac: Install DBR for Mac and Xcode.

Install node-gyp:

npm install -g node-gyp

Create binding.gyp for multi-platform compilation:

{
"targets": [
{
&#39;target_name&#39;: "dbr",
&#39;sources&#39;: [ "dbr.cc" ],
&#39;conditions&#39;: [
[&#39;OS=="linux"&#39;, {
&#39;defines&#39;: [
&#39;LINUX_DBR&#39;,
],
&#39;include_dirs&#39;: [
"/home/xiao/Dynamsoft/BarcodeReader4.0/Include"
],
&#39;libraries&#39;: [
"-lDynamsoftBarcodeReaderx64", "-L/home/xiao/Dynamsoft/BarcodeReader4.0/Redist"
],
&#39;copies&#39;: [
{
&#39;destination&#39;: &#39;build/Release/&#39;,
&#39;files&#39;: [
&#39;/home/xiao/Dynamsoft/BarcodeReader4.0/Redist/libDynamsoftBarcodeReaderx64.so&#39;
]
}]
}],
[&#39;OS=="win"&#39;, {
&#39;defines&#39;: [
&#39;WINDOWS_DBR&#39;,
],
&#39;include_dirs&#39;: [
"F:/Program Files (x86)/Dynamsoft/Barcode Reader 4.1/Components/C_C++/Include"
],
&#39;libraries&#39;: [
"-lF:/Program Files (x86)/Dynamsoft/Barcode Reader 4.1/Components/C_C++/Lib/DBRx64.lib"
],
&#39;copies&#39;: [
{
&#39;destination&#39;: &#39;build/Release/&#39;,
&#39;files&#39;: [
&#39;F:/Program Files (x86)/Dynamsoft/Barcode Reader 4.1/Components/C_C++/Redist/DynamsoftBarcodeReaderx64.dll&#39;
]
}]
}],
[&#39;OS=="mac"&#39;, {
&#39;defines&#39;: [
&#39;MAC_DBR&#39;,
],
&#39;include_dirs&#39; : [
"/Applications/Dynamsoft/Barcode/ Reader/ 4.1/Include"
],
&#39;libraries&#39;: [
"-lDynamsoftBarcodeReader"
]
}]
]
}
]
}

Replace the DRB installation directory with the actual directory on your machine.

Configure the build environment:

node-gyp configure

On Mac you will encounter the following error:

error: xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance

The solution is:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

Build project:

node-gyp build

Online barcode parsing

You have successfully built Node’s barcode parsing module and can now create a simple barcode reading application.

Install Express and Formidable:

npm install express
npm install formidable

Create a simple application using Express:

var formidable = require(&#39;formidable&#39;);
var util = require(&#39;util&#39;);
var express = require(&#39;express&#39;);
var fs = require(&#39;fs&#39;);
var app = express();
var path = require(&#39;path&#39;);
var dbr = require(&#39;./build/Release/dbr&#39;);
var http = require(&#39;http&#39;);
fs.readFile(&#39;./license.txt&#39;, &#39;utf8&#39;, function(err, data) {
app.use(express.static(__dirname));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "X-Requested-With, content-type");
res.header("Access-Control-Allow-Credentials", true);
next();
});
var server = app.listen(2016, function() {
var host = server.address().address;
var port = server.address().port;
console.log(&#39;listening at http://%s:%s&#39;, host, port);
});
});

Use Formidable to extract image data from the form:

app.post(&#39;/upload&#39;, function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
var dir = &#39;uploads&#39;;
fs.mkdir(dir, function(err) {
var flag = fields.uploadFlag;
var barcodeType = parseInt(fields.barcodetype);
console.log(&#39;flag: &#39; + flag);
if (flag === &#39;1&#39;) { // read barcode image file
fs.readFile(files.fileToUpload.path, function(err, data) {
// save file from temp dir to new dir
var fileName = path.join(__dirname, dir, files.fileToUpload.name);
console.log(fileName);
fs.writeFile(fileName, data, function(err) {
if (err) throw err;

});
});
} else { // read barcode image url
var tmpFileName = path.join(__dirname, dir, &#39;tmp.jpg&#39;);
var tmp = fs.createWriteStream(tmpFileName);
var url = fields.fileToDownload;
console.log(&#39;url: &#39; + url);
http.get(url, function(response) {
response.pipe(tmp);
tmp.on(&#39;finish&#39;, function() {
tmp.close(function() {

});
});
});
}
});
});
});

Import the barcode module to parse the image file:

decodeBarcode(res, license, tmpFileName, barcodeType);

Run the application:

node server.js

Access http: //localhost:2016/index.htm:

The above is a detailed explanation of the Node.js barcode recognition program construction idea introduced by the editor. I hope it will be helpful to everyone.

【Recommended related tutorials】

1. JavaScript video tutorial
2. JavaScript online manual
3. bootstrap tutorial

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function