Using Node.js to access Azure IoT Hub

By now the Cloud strategy of Microsoft must be very clear. It’s not about Windows, it’s not about Office, it’s not about Microsoft programming languages even. Microsoft is opening up towards all devices, operating systems, programming platforms, etc. Everybody is welcome in the cloud.

Although this is going on for quite some time, it is still a surprise for quite a few non-Microsoft developers. So today I decided to program against the Azure IoT Hub using another language, just to check out their experience.

Microsoft supports multiple programming languages, there are multiple SDK’s available:

If your favorite language is not listed here, but it talks MQTT, AMQP or HTTP, chances a big you can build your own SDK.

Today I picked up Node.js because I know a bit of javascript 🙂 Let’s check out what Javascript developers have to do to connect to an Azure IoT Hub.

Install Node.js

NodeJs is a nice lightweight environment in which javascript can be executed.

Go to the website and install Node.js:

Node.js can be installed on a wide range of devices, I install it on a PC running Windows 10:

Make sure the file explorer path to Node.js is added to the Path environment setting.

Start a new Node.js job

Create a new folder using the Windows Explorer on your PC and open a dos box for that folder (tip: just enter CMD in the address bar and a dos box will open using that path as the starting point).

Enter ‘npm init’ to create a new Node.js package:

A couple of questions will be asked, just select the defaults (so press ‘enter’ for each question).

In the end, a package.json will be created:

  "name": "nodejsiot",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "",
  "license": "ISC"

The most important line is the ‘index.js’. This file (not available yet) is the starting point for this Node.js job.

Import specific Node.js libraries

Our job will access the IoT Hub (we both send telemetry and receive commands). Microsoft provides libraries for the communication so let’s import them by executing these two lines at the Dos prompt:

npm install azure-iothub
npm install azure-iot-device-amqp

The first command will install the logic to communicate to an Azure IoT Hub. The second command will install the logic to communicate using the AMQP protocol. Failing to install it will result in an error like ‘Error: Cannot find module ‘azure-iot-device-amqp’.

Afterward, a folder named ‘node_modules’ is created. It is filled with 100+ subfolders. We can safely ignore them 🙂

Create index.js

Using your favorite text editor, now create a new file named ‘index.js’, in the selected folder. Write the following code:

'use strict';

var clientFromConnectionString = require('azure-iot-device-amqp').clientFromConnectionString;
var Message = require('azure-iot-device').Message;

var connStr = '[IoT Hub Device Connection string]';

var client = clientFromConnectionString(connStr);

function printResultFor(op) {
  return function printResult(err, res) {
    if (err) console.log(op + ' error: ' + err.toString());
    if (res) console.log(op + ' status: ' +;

var i = 0;

var connectCallback = function (err) {
  if (err) {
    console.log('Could not connect to IoT Hub: ' + err);
  } else {
    console.log('Client connected to IoT Hub');

    client.on('message', function (msg) {
      client.complete(msg, printResultFor('completed'));

      if ([0] == 42) {
        console.log("\x1b[33m",'Command = ' +;
        console.log("\x1b[0m", '------------------');
      } else {
        console.log("\x1b[31m",'Command = ' +;
        console.log("\x1b[0m", '------------------');

    // Create a message and send it to the IoT Hub every second

      var data = JSON.stringify({ numberOfCycles: i });
      var message = new Message(data);

      console.log("Telemetry sent: " + message.getData());
      client.sendEvent(message, printResultFor('send'));
    }, 2000);

console.log("\x1b[31m",'NodeJs IoTHub DEMO');
console.log("\x1b[0m", '==================');;

Save the ‘index.js’ file. It’s not ready to be executed yet, we still have a couple of things to do.

Add a device to your IoT Hub

Our Node.js job will behave like a real device. So it needs device credentials to access an Azure IoT Hub. First, create an Azure IoT Hub:

Secondly, create a device using the device explorer (a new feature in the Azure portal). Just enter a unique name and ignore the other settings:

After creation, a device is available with specific credentials. Copy a connection string into the code at ‘[IoT Hub Device Connection string]’:

Save the file. The code is ready to run.

Run your Node.js device and send telemetry

At the Dos prompt, execute the Node.js job:

node index.js

See how messages are sent to the IoT Hub:

You can check the arrival of the telemetry using the Device Explorer tool.

Retrieving commands

Using the same tool, it’s possible to send commands:

We can make decisions based on the incoming commands:

In the code, the commands (eg. ‘*’ and ‘A’) arrive as a byte array. The console output can write these commands as text directly, this can be confusing regarding the right type of the variables.

Adding Routing

It’s nice to see that Microsoft is committed to these SDK’s. In Github, the last updates made to the Node.js SDK are just a few days ago. To show Microsoft is updating the code with new features, let’s check out IoT Hub routing. Alter the code a bit by adding a property which can be detected by the IoT Routing logic:

  var message = new Message(data);
  // Use Routing'severity', 'high');

I have already put a route in place which sends messages with a high severity to an Eventhub:

When I execute the job, messages start arriving at an Azure Function which is attached to and triggered by the Eventhub:


It’s great to see that the Azure (IoT) platform is accessible for multiple programming languages. This makes it easier for me to cherry pick the right (programming) tool for the right job.

In my opinion, the programming experience is good. I only had to do some digging for documentation regarding the right code. Luckily, the SDK’s are open sourced in Github so I can always check the source code.