Using Azure Event Hub with Node.js

Hakim Elakhrass
arinti
Published in
3 min readAug 10, 2017

--

IOT seems to be everywhere thesedays. From your car to your fridge. Building applications that use the power of IOT devices can be very useful. In this blog post I will connect to an Azure Event Hub, using node.js to send and receive information.

Normally you would send information from an IOT device and then receive it into node.js (or a number of other languages). For testing however simulating an IOT device by sending data from node.js can be very useful. This will allow you to demo applications without needing a real-time IOT device running.

Requirments:

Be sure to run the folllowing code in the terminal of the directory you have your code in:

npm install azure-event-hubs

This will install the required packages.

The Sender

This above snippet of code connects to your azure event hub. It creates an artificial stream of data and sends it with a delay of 1 second between callbacks. You should fill in your own connection string from Azure Event hub in place of the XXX.

The output in the terminal looks like this:

Every 1 second it prints to the console the data it is sending to Azure. Now it would not be so hard to extend this script to a document with historical data from an IOT device. This way you can simulate what it would actually look like to stream data from your IOT device to the cloud.

I have done exactly that to start streaming my own data.

You can see in the code above I have used a local JSON document to stream data into Azure. It will stream one JSON object every second. The receiver code does not have to change. Now you can take this data and push it further down your pipeline to demo what it would like if it was a real IOT device.

The Receiver

The receiver will then receive messages from Azure Event Hub.

Just like in the previous code you should replace XXX with your own connection string. This will then receive messages from your Azure Event Hub.

The output in the terminal will look like this:

You can see the output from receiving my own data here:

Running the Code

After writing both sets of code you should save them in the save directory. To initialize them you should run the follow commands in your terminal:

node sender.jsnode reciever.js 

Final Thoughts:

In this blog you learned how to stream your own data in an Azure Event Hub. This will allow you to simulate an IOT device for demoing production code to the public. It is more reliable than setting up a dummy IOT device and basically gives you the same results.

We all know what happens when we try to a live demo. This takes away one more uncertainty while demoing! As always you can contact me with any questions you have!

--

--

Passionate about life and knowledge. Interested in meeting new people and exchanging ideas.