JSON数组到nodejs可读对象流怎么实现?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (246)

每次从蓝牙设备收到数据包时,都会触发一个事件。数据包以JSON数组的形式出现,并且总是包含10个与下面类似的对象。

var s1_data = [{"record":0,"sensor":1,"timestamp":26566,"date":{"day":7,"hour":10,"minute":45,"month":5,"second":38,"year":18}},
{"record":1,"sensor":1,"timestamp":26567,"date":{"day":7,"hour":10,"minute":45,"month":5,"second":38,"year":18}},
{"record":2,"sensor":1,"timestamp":26568,"date":{"day":7,"hour":10,"minute":45,"month":5,"second":38,"year":18}},
{"record":3,"sensor":1,"timestamp":26569,"date":{"day":7,"hour":10,"minute":45,"month":5,"second":38,"year":18}},
{"record":4,"sensor":1,"timestamp":26570,"date":{"day":7,"hour":10,"minute":45,"month":5,"second":38,"year":18}},
{"record":5,"sensor":1,"timestamp":26571,"date":{"day":7,"hour":10,"minute":45,"month":5,"second":38,"year":18}},
{"record":6,"sensor":1,"timestamp":26572,"date":{"day":7,"hour":10,"minute":45,"month":5,"second":38,"year":18}},
{"record":7,"sensor":1,"timestamp":26573,"date":{"day":7,"hour":10,"minute":45,"month":5,"second":38,"year":18}},
{"record":8,"sensor":1,"timestamp":26574,"date":{"day":7,"hour":10,"minute":45,"month":5,"second":38,"year":18}},
{"record":9,"sensor":1,"timestamp":26575,"date":{"day":7,"hour":10,"minute":45,"month":5,"second":38,"year":18}}]

我需要将每个单独的对象推送到另一个流正在使用的node.js流中。

可以举例说明如何将它们推送到可读对象流(或者我需要使用PassThrough流)吗?

编辑在下面添加示例代码

var Readable = require('stream').Readable;
var util = require('util');
var through2 = require('through2');

var s1 = require('./sensor1.js');
var s2 = require('./sensor2.js');

var minLength = s1.length;
//console.log(s1);
var s1stream = new Readable({ objectMode: true });
var s2stream = new Readable({ objectMode: true });


s1stream._read = function () {
    this.push();
};

s2stream._read = function () {
    this.push();
};

if (s2.length < minLength){
  minLength = s2.length;
}

var n1 = 0;
setInterval(function() {
    if (n1++ < minLength) {
        console.log(s1[n1].record);
        s1stream.push(s1[n1]);
    } else if (n1++ === minLength) {
        s1stream.push(null);
    }
}, 1000);

var n2 = 0;
setInterval(function() {
    if (n2++ < minLength) {
        s2stream.push(s2[n2]);
    } else if (n2++ === minLength) {
        s2stream.push(null);
    }
}, 1000);


s1stream.pipe(through2.obj(function (chunk, enc, callback) {
    this.push(chunk.toString())
    callback()
  })).pipe(process.stdout);
提问于
用户回答回答于

你将需要实现一个“包装”你的蓝牙源的可读流。当数据包接收事件被触发时,将循环访问对象数组,并调用可读流的push方法,传入每个对象。

请注意,由于你将发送实际的JSON对象,因此在你按照此处所述编写实现时,需要启用objectMode选项

扫码关注云+社区

领取腾讯云代金券