This article explains how to establish a connection with Microsoft Azure cloud services using nodeJS* API. While this was written for the Intel® Edison board, it should work on any platform that runs nodeJS. This includes creating a storage account, store and retrieve data.
Create an Azure storage account
Log in to Azure Management Portal and click New at the bottom of the page.
Select DATA SERVICES -> STORAGE -> QUICK CREATE and type a name to use in the URI for the storage account. Make sure that a green tick mark is enabled indicating a unique name.
Click CREATE STORAGE ACCOUNT.
Set up your development environment
Install azure-storage npm module into your project
npm install azure-table-node
This article uses a third party node module azure-table-node for convenience. You can use the official azure client library for node.
Setup an Azure storage connection
Create a node reference variable for the module.
var azureTable = require('azure-table-node');
The function setDefaultClient
requires storage name and access key which can be obtained from Azure portal.
azureTable.setDefaultClient({ accountUrl: 'https://' + this.accountName + '.table.core.windows.net/', accountName: this.accountName, accountKey: this.config.accessKey, timeout: 10000 });
Create table
Get the default client created above. Use this client to perform operations on Azure storage.
var defaultClient = azureTable.getDefaultClient(); Create a table with a name using the client. // use the client to create the table defaultClient.createTable('tableName', cb);
Store Data
Azure table storage takes data as entities. Each entity will have a Row and Partition Key. A Row Key must be unique to every row.
entity['PartitionKey'] = entity.sensor_id.toString(); entity['RowKey'] = Date.parse(entity.timestamp).toString(); entity['value'] = 86; client.insertOrReplaceEntity(‘tableNmae’, entity, function(err, data) { // err is null // data contains etag });
Query Data
Timestamp based query
dataQuery = azureTable.Query.create('PartitionKey', '==', readQuery.sensor_id).and('timestamp', '>=', readQuery.timestamp);
Sensorid based query
dataQuery = azureTable.Query.create('PartitionKey', '==', readQuery.sensor_id);
Call queryEntities
on the client with options to return only required fields viz., sensor_id
, timestamp
, and value
.
client.queryEntities(‘tableName’, { query: dataQuery, onlyFields: ['sensor_id', 'timestamp', 'value'] }, function(err, results, continuation) {});
References
Microsoft documentation - https://azure.microsoft.com/en-us/develop/nodejs/
Azure node project - https://www.npmjs.com/package/azure
Azure Table Storage client - https://www.npmjs.com/package/azure-table-node
Azure - https://msdn.microsoft.com/en-us/library/azure/dn578280.aspx
Azure Storage Explorer - https://azurestorageexplorer.codeplex.com/