How to Use Node RED to Read Barcode and QR Code in JavaScript

Node-RED is a flow-based programming tool built-on Node.js. It provides a browser-based editor that helps users create awesome applications by wiring different nodes. This article shares how to build a barcode QR reading node with Dynamsoft Barcode Reader.

Node-RED Installation

Install and run Node-RED.

Windows

npm install -g --unsafe-perm node-red

node-red

Linux

npm install -g --unsafe-perm node-red

# Or
sudo snap install node-red

node-red

The first time running node-red, it will create a folder named .node-red in your home directory.

Windows

%userprofile%\.node-red

Linux

~/.node-red

If the default port 1880 is in use, you will get the following error message:

Welcome to Node-RED
===================

5 Nov 14:29:12 - [info] Node-RED version: v0.19.5
5 Nov 14:29:12 - [info] Node.js  version: v8.11.3
5 Nov 14:29:12 - [info] Windows_NT 10.0.17763 x64 LE
5 Nov 14:29:13 - [info] Loading palette nodes
5 Nov 14:29:14 - [warn] rpi-gpio : Raspberry Pi specific node set inactive
5 Nov 14:29:15 - [warn] ------------------------------------------------------
5 Nov 14:29:16 - [warn] [node-red/tail] Not currently supported on Windows.
5 Nov 14:29:16 - [warn] ------------------------------------------------------
5 Nov 14:29:16 - [info] Settings file  : \Users\xiao\.node-red\settings.js
5 Nov 14:29:16 - [info] Context store  : 'default' [module=memory]
5 Nov 14:29:16 - [info] User directory : \Users\xiao\.node-red
5 Nov 14:29:16 - [warn] Projects disabled : editorTheme.projects.enabled=false
5 Nov 14:29:16 - [info] Flows file     : \Users\xiao\.node-red\flows_DESKTOP-3PCHU10.json
5 Nov 14:29:16 - [info] Creating new flow file
5 Nov 14:29:16 - [info] Starting flows
5 Nov 14:29:16 - [info] Started flows
5 Nov 14:29:16 - [error] Uncaught Exception:
5 Nov 14:29:16 - [error] Error: listen EACCES 0.0.0.0:1880
    at Object._errnoException (util.js:992:11)
    at _exceptionWithHostPort (util.js:1014:20)
    at Server.setupListenHandle [as _listen2] (net.js:1338:19)
    at listenInCluster (net.js:1396:12)
    at doListen (net.js:1505:7)
    at _combinedTickCallback (internal/process/next_tick.js:141:11)
at process._tickCallback (internal/process/next_tick.js:180:9)

The workaround is to change the port number in .node-red/settings.js. For example, we can change the default port number to 18800:

node red

Build a Barcode Node

We use npm command to generate a new project and install the barcode4nodejs module, which is a wrapper for Dynamsoft Barcode Reader C++ SDK. The performance of barcode4nodejs is much better than any other JavaScript barcode readers.

npm init
npm install barcode4nodejs

In the package.json file, add the node-red section:

"node-red": {
    "nodes": {
      "barcode": "barcode.js"
    }
  },

The node-red section tells Node-RED where to find the node module. In this case, the module is in the same folder as the package.json file. The barcode.js file is the entry point of the module.

module.exports = function(RED) {
  var dbr = require('dbr');
  var barcodeTypes = dbr.formats.OneD | dbr.formats.PDF417 | dbr.formats.QRCode | dbr.formats.DataMatrix | dbr.formats.Aztec; 

  function BarcodeNode(config) {
    RED.nodes.createNode(this, config);
    this.license = config.license;
    this.template = config.template;
    var node = this;
    node.on('input', function(msg) {
      if (msg.filename) {
        dbr.initLicense(node.license);
        dbr.decodeFileAsync(msg.filename, barcodeTypes, function(err, results) {
          msg.payload = results;
          node.send(msg);
        }, node.template);
      } else {
        msg.payload = msg.payload.toLowerCase();
        node.send(msg);
      }
    });
  }
  RED.nodes.registerType('barcode', BarcodeNode);
}

When an input event is triggered, we can get the image file name from the file node. Then we can call the decodeFileAsync method to decode the barcode from the image file. The decodeFileAsync method is an asynchronous method. It takes a callback function as the last parameter. The callback function will be called when the decoding is finished.

The UI of the node is defined in the barcode.html file.

<script type="text/javascript">
    RED.nodes.registerType('barcode',{
        category: 'Dynamsoft',
        color: '#a6bbcf',
        defaults: {
            name: {value:""},
            license: {value:""},
            template: {value: ""}
        },
        inputs:1,
        outputs:1,
        icon: "function.png",
        label: function() {
            return this.name||"barcode";
        }
    });
</script>

<script type="text/x-red" data-template-name="barcode">
    <div class="form-row">
        <label for="node-input-name"><i class="icon-tag"></i> Name</label>
        <input type="text" id="node-input-name" placeholder="Barcode Reader">
    </div>
    <div class="form-row">
		<label for="node-input-license"><i class="icon-tag"></i> License</label>
		<input type="text" id="node-input-license" placeholder="DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==">
    </div>
    <div class="form-row">
		<label for="node-input-template"><i class="icon-tag"></i> Template</label>
		<input type="text" id="node-input-template" placeholder="https://www.dynamsoft.com/barcode-reader/docs/core/parameters/structure-and-interfaces-of-parameters.html?ver=latest">
	</div>
</script>

<script type="text/x-red" data-help-name="barcode">
    <p>A simple node that read barcodes from image files.</p>
</script>

A valid license is required to use the barcode reader.

Try NODE-RED Barcode Node

So far, we have finished the barcode node. Before publishing the node module, we can test it locally.

  1. Install the local project.

    Windows

     cd %userprofile%\.node-red
     npm install <the local project>
     node-red
    

    Linux

     cd ~/.node-red
     npm install <the local project>
     node-red
    
  2. Open the node-red editor in your web browser.
  3. Drag inject node, file node, barcode node and debug node to the workspace, and connect them together.

  4. Set the image path in the file node:

    node red debug

  5. Click barcode node to set the license and barcode parameter template. If the template is empty, the default template will be used.

    node red barcode license

  6. Run the workflow to output the barcode QR detection results in the console:

    node red barcode results

Publish Barcode Node and Use It in NODE-RED

If everything works fine, we can publish the module to npmjs.com

cd <node red barcode project>
npm publish

You can use node-red-contrib-barcode as follows:

cd <HOME>/node-red
npm install node-red-contrib-barcode
node-red

References

https://nodered.org/docs/

Source Code

https://github.com/yushulx/node-red-contrib-barcode