Nodejs可读流管道响应

时间:2018-02-10 16:39:38

标签: node.js express stream readable

我必须维护遗留代码。基础知识:它应该处理传入的流(音频和/或视频)。第三方设备在请求时发送流。然后客户端应该使用它。

代码未完成,但对我来说,似乎很好。 NodeJS版本是最新的(atm):8.9.4

// init.js(主要的js文件)

global.readStream = new readStream();

读取流对象看起来像这个旧对象: // readStream对象

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

function myReadStream() {
  Readable.call(this);
  this.data = null;
}
util.inherits(myReadStream, Readable);

myReadStream.prototype.addData = function (newData) {
    this.data = newData;
    console.log('new data: ', this.data);
};

myReadStream.prototype._read = function () {
  this.push(this.data);
};

所以,两个终点:

app.get('incomingdata', function (req, res) {
     myReadStream.addData = res.newIncomingData; 
     // just writing the stream data directly
     console.log('incoming: ', res.newIncomingData);
});

app.get('outgoingData', function (req, res) {
     myReadStream
  .on('readable', function () {
    var obj;
    while (null !== (obj = myReadStream.read())) {
      myReadStream.pipe(res); // direct pipe to res
      // alternative idea: res.send(obj);
      // alternative #2: res.write(obj);
      console.log('outgoing: ', obj);
    }
  });
});

结果是,“outgoingData”的调用总是只重复readStream数据的一个阶段(最近在传出数据调用之前需要的东西)但不刷新......

E.g:

Incoming: <Buffer 00 e3 ff ab a2 ....>
new data: <Buffer 00 e3 ff ab a2 ....>
Incoming: <Buffer 01 3b ca c1 b0 ....>
new data: <Buffer 01 3b ca c1 b0 ....>
Outgoing: <Buffer 01 3b ca c1 b0 ....>
Incoming: <Buffer 99 fa e8 77 00 ....>
new data: <Buffer 99 fa e8 77 00 ....>
Outgoing: <Buffer 01 3b ca c1 b0 ....>
Incoming: <Buffer ef b0 00 22 33 ....>
new data: <Buffer ef b0 00 22 33 ....>
Outgoing: <Buffer 01 3b ca c1 b0 ....>
Incoming: <Buffer 25 7b 91 aa 00 ....>
new data: <Buffer 25 7b 91 aa 00 ....>
Outgoing: <Buffer 01 3b ca c1 b0 ....>

我只有Socket.Io的经验,可读性和可写性都不多。据我所知,这个代码是在1.5 x之前开发的,版本为4.x. 代码似乎很好,但错过了一些东西。知道什么是错的,我该怎么纠正呢?

(p.s:我不喜欢维护遗留代码)

0 个答案:

没有答案
相关问题