Search code examples
jsonhttpmqttreal-time-datanode.js-stream

how to publish realtime streaming json data received from a URL over mqtt using node.js


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
 }))

Solution

  • 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.