4. Review the code

By reviewing the frontend/app.js code, you can understand how to use Message Hub with the MQ Light API.

First, the application determines whether it is running in Bluemix by checking for the presence of the process.env.VCAP_SERVICES variable. If the variable is found, the application then gets the necessary details from the environment variable. Otherwise, it uses the default local settings.

if (process.env.VCAP_SERVICES) {
var services = JSON.parse(process.env.VCAP_SERVICES);
console.log('Running BlueMix');
for (var key in services) {
if (key.lastIndexOf(mqlightServiceName, 0) === 0) {
mqlightService = services[key][0];
opts.service = mqlightService.credentials.nonTLSConnectionLookupURI;
opts.user = mqlightService.credentials.username;
opts.password = mqlightService.credentials.password;
} else if (key.lastIndexOf(messageHubServiceName, 0) === 0) {
messageHubService = services[key][0];
opts.service = messageHubService.credentials.mqlight_lookup_url;
opts.user = messageHubService.credentials.user;
opts.password = messageHubService.credentials.password;
if (!opts.hasOwnProperty('service') ||
!opts.hasOwnProperty('user') ||
!opts.hasOwnProperty('password')) {
throw 'Error - Check that app is bound to service';
} else {
var fishaliveHost = process.env.FISHALIVE_HOST || 'localhost'
opts.service = 'amqp://' + fishaliveHost + ':5672'

The application creates an MQ Light client by using this method, which is used for both publishing and subscribing to a topic:

var mqlightClient = mqlight.createClient(opts, function (err) {

In the backend/app.js file, you can see the worker subscribing and specifying the processMessage as the callback that is called when a message arrives:

mqlightClient.on('message', processMessage)
var subOpts = { credit: 1, autoConfirm: false, qos: 1 }
mqlightClient.subscribe(SUBSCRIBE_TOPIC, SHARE_ID, subOpts, function (err) {
if (err) {
console.error('Failed to subscribe: ' + err)
} else {

For the worker, the subscription uses a credit of 1 and autoConfirm is set to false meaning that the worker deals with one message at a time until confirming that it has been handled.