简体   繁体   English

如何使用node.js发布通过mqtt从URL接收的实时流json数据

[英]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? 我有以下代码可以接收来自url的数据并打印json格式的数据。我想使用node.js将相同的数据发布到mqtt,是否有相同的示例代码?

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

Just use a node.js library for mqtt such as MQTT.js https://github.com/adamvr/MQTT.js 只需将node.js库用于mqtt,例如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 您也可以通过安装mosca https://github.com/mcollina/mosca在node.js中运行自己的多协议代理

You could use the mqtt node library MQTT.js 您可以使用mqtt节点库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. 上面的代码假定代理在端口1883上的本地计算机上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM