1

I have the following code which accepts data from the url and print the json formatted data.I want to publish the same data to mqtt using node.js.Is there any sample code for the same?

`var request = require('request')
var JSONStream = require('JSONStream')
`var es = require('event-stream')` 
 `request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
`.pipe(JSONStream.parse('rows.*'))
 .pipe(es.mapSync(function (data) {
 console.log(data);
 console.error(data)
 return data
 }))
Durga
  • 319
  • 1
  • 6
  • 18

2 Answers2

1

Just use a node.js library for mqtt such as MQTT.js https://github.com/adamvr/MQTT.js

Also you can run your own multi-protocol broker in node.js by installing mosca https://github.com/mcollina/mosca

Teixi
  • 1,077
  • 8
  • 21
1

You could use the mqtt node library MQTT.js

Your current code becomes something like that:

var request = require('request');
var JSONStream = require('JSONStream');
var es = require('event-stream');
var mqtt = require('mqtt');
request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
    .pipe(JSONStream.parse('rows.*'))
    .pipe(es.mapSync(function (data) {
        console.log(data);
        console.error(data);

        //MQTT publish starts here
        var client = mqtt.createClient(1883, 'localhost');
        client.publish('demoTopic', JSON.stringify(data));
        client.end();

        return data;
 }))

The above code assumes the broker is running on the local machine on port 1883.

Durga
  • 319
  • 1
  • 6
  • 18
manu2013
  • 1,215
  • 11
  • 8