Node. js code identification program construction ideas _ node. js

Source: Internet
Author: User
Tags readfile install node node server
This article mainly introduces Node. for details about how to build a js barcode recognition program, refer to the following article. We will show you a very simple method to build a custom Node module, this module encapsulates the Dynamsoft Barcode Reader SDK and supports Windows, Linux, and OS X. At the same time, we will demonstrate how to integrate this module to implement an online Barcode reading application.

More and more Web developers are choosing Node to build websites because JavaScript is increasingly convenient for developing complex server-side Web applications. To expand Node functions on different platforms, Node allows developers to use C/C ++ to create extensions.

Introduction

Dynamsoft Barcode Reader provides a shared library for bar code parsing for Windows, Linux, and OS X. Its biggest advantage is that it is applicable to a variety of advanced programming languages, including JavaScript, Python, Java, Ruby, PHP, etc., as long as it can encapsulate C/C ++ API as an extension. No matter what programming language, you only need a few lines of code to complete bar code parsing.

Supports 1D/2D barcode types

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

Supported image types

BMP, JPEG, PNG, GIF, TIFF, PDF

Running Environment

Windows, Linux & Mac
Node v5.5.0

Node. js bar code Extension

The Node. js extension uses the shared object of Dynamic Links written in C/C ++. If you have never touched on this technology, read the official tutorial.

Create Extension

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

# Include
 
  
# Include
  
   
# Include "If_DBR.h" # include "BarcodeFormat. h" # include "BarcodeStructs. h" # include "ErrorCode. h" using namespace v8; void DecodeFile (const FunctionCallbackInfo
   
    
& Amp; args) {} void Init (Handle
    Exports) {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();Local
      
        cb = 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 imageint ret = DBR_DecodeFile(pFileName, &ro, &pResults);

Convert the barcode to a 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 a v8 object:

Local barcodeResults = 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: DBR for Windows, visual Studio, and Python v2.7must 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": [{'target_name': "dbr",'sources': [ "dbr.cc" ],'conditions': [['OS=="linux"', {'defines': ['LINUX_DBR',],'include_dirs': ["/home/xiao/Dynamsoft/BarcodeReader4.0/Include"],'libraries': ["-lDynamsoftBarcodeReaderx64", "-L/home/xiao/Dynamsoft/BarcodeReader4.0/Redist"],'copies': [{'destination': 'build/Release/','files': ['/home/xiao/Dynamsoft/BarcodeReader4.0/Redist/libDynamsoftBarcodeReaderx64.so']}]}],['OS=="win"', {'defines': ['WINDOWS_DBR',],'include_dirs': ["F:/Program Files (x86)/Dynamsoft/Barcode Reader 4.1/Components/C_C++/Include"],'libraries': ["-lF:/Program Files (x86)/Dynamsoft/Barcode Reader 4.1/Components/C_C++/Lib/DBRx64.lib"],'copies': [{'destination': 'build/Release/','files': ['F:/Program Files (x86)/Dynamsoft/Barcode Reader 4.1/Components/C_C++/Redist/DynamsoftBarcodeReaderx64.dll']}]}],['OS=="mac"', {'defines': ['MAC_DBR',],'include_dirs' : ["/Applications/Dynamsoft/Barcode/ Reader/ 4.1/Include"],'libraries': ["-lDynamsoftBarcodeReader"]}]]}]}

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

Configure the Build Environment:

Node-gyp configure

You may encounter the following error on Mac:

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

Solution:

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

Build project:

Node-gyp build

Online barcode resolution

You have successfully built the bar code parsing module of Node. Now you can create a simple bar code reading application.

Install Express and Formidable:

Npm install express
Npm install formidable

Use Express to create a simple application:

var formidable = require('formidable');var util = require('util');var express = require('express');var fs = require('fs');var app = express();var path = require('path');var dbr = require('./build/Release/dbr');var http = require('http');fs.readFile('./license.txt', 'utf8', 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('listening at http://%s:%s', host, port);});});

Use Formidable to extract image data from the form:

app.post('/upload', function(req, res) {var form = new formidable.IncomingForm();form.parse(req, function(err, fields, files) {var dir = 'uploads';fs.mkdir(dir, function(err) {var flag = fields.uploadFlag;var barcodeType = parseInt(fields.barcodetype);console.log('flag: ' + flag);if (flag === '1') { // read barcode image filefs.readFile(files.fileToUpload.path, function(err, data) {// save file from temp dir to new dirvar 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 urlvar tmpFileName = path.join(__dirname, dir, 'tmp.jpg');var tmp = fs.createWriteStream(tmpFileName);var url = fields.fileToDownload;console.log('url: ' + url);http.get(url, function(response) {response.pipe(tmp);tmp.on('finish', function() {tmp.close(function() {});});});}});});});

Import the barcode module to parse image files:

DecodeBarcode (res, license, tmpFileName, barcodeType );

Run the application:

Node server. js

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


The above is a detailed explanation of how to build the Node. js barcode recognition program. I hope it will help you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.