OdeToCode IC Logo

Azure WebJobs With Node.js

Monday, April 7, 2014

Azure WebJobs are background services you can run in the cloud. The experience is easy and smooth. Scott has a thorough overview in “Introducing Windows Azure WebJobs”. 

In a previous post we looked at using JavaScript to read messages from Azure Queue storage.  We can use the code from that previous post in an Azure WebJob by creating a run.js file. WebJobs will automatically execute a run.js file using Node.

var config = require("./config.json");
var queue = require("./queue")(config);

var checkQueue = function () {
    queue.getSingleMessage()
        .then(processMessage)
        .catch(processError)
        .finally(setNextCheck);
};

var processMessage = function (message) {   
    if (message) {        
        console.dir(message);

        // processing commands, then ...

        return queue.deleteMessage(message);
    }
};

var processError = function(reason) {
    console.log("Error:");
    console.log(reason);
};

var setNextCheck = function () {
    setTimeout(checkQueue, config.checkFrequency);
};

checkQueue();

Aimagell that’s needed to deploy the job is to zip up run.js with all its dependencies (including the node_modules directory) and upload the zip into an Azure website. 

The above code expects to run continuously and poll a queue. You can configure each job to run continuously, on a schedule, or on demand in the Azure portal. Azure will store any output from the program in a log file that is one click away. 

Another Useful Link

How to deploy Windows Azure WebJobs by Amit Apple is a behind the scenes look at how to deploy a web job using Git or FTP.