节点可读流困境

时间:2016-04-09 20:58:13

标签: node.js fs

我在溪流上看这个非常漂亮的例子。

https://gist.github.com/joyrexus/10026630

可读的例子如下:

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

function Source(content, options) {
  Readable.call(this, options)
  this.content = content
}

inherits(Source, Readable)

Source.prototype._read = function (size) {
  if (!this.content) this.push(null)
  else {
    this.push(this.content.slice(0, size))
    this.content = this.content.slice(size)
  }
}

var s = new Source("The quick brown fox jumps over the lazy dog.")
console.log(s.read(10).toString())
console.log(s.read(10).toString())
console.log(s.read(10).toString())
console.log(s.read(10).toString())
console.log(s.read(10).toString())

// The quick 
// brown fox 
// jumps over
//  the lazy 
// dog.


var q = new Source("How now brown cow?")
q.pipe(process.stdout);

让我感到困惑的是,流的重点是 而不是 来一次缓冲内存中的所有内容,以及提供一些异步,所以不是关于管道流的所有事情都是在事件循环的同一回合中处理的。

  const writable = new stream.Writable({

        write: function(chunk, encoding, cb){

            console.log('data =>', String(chunk));

            cb();
        }

    });


    var readable = new stream.Readable({

        read: function(size){

            // what do I do with this? It's required to implement

        }
    });

    readable.setEncoding('utf8');

    readable.on('data', (chunk) => {
        console.log('got %d bytes of data', chunk.length, String(chunk));
    });

    readable.pipe(writable);

    readable.push('line1');
    readable.push('line2');
    readable.push('line3');
    readable.push('line4');

但我不明白的是,我应该如何在可读性上实现read方法?

似乎我将以完全不同于示例的方式实现读取,因此似乎有些东西已经关闭。

如何手动读取带有可读流的数据?

1 个答案:

答案 0 :(得分:0)

嗯,我知道有些事情有点过时,我相信这更接近规范的做法:

SELECT c.Name, count(t.ID) 
FROM clients c 
left join transactions t on c.CustomerID = t.Client_id
group by t.client_id

我不相信开发者应该明确地致电 const writable = new stream.Writable({ write: function(chunk, encoding, cb){ console.log('data =>', String(chunk)); cb(); }, end: function(data){ console.log('end was called with data=',data); } }); var index = 0; var dataSource = ['1','2','3']; var readable = new stream.Readable({ read: function(size){ var data; if(data = dataSource[index++] ){ this.push(data); } else{ this.push(null); } } }); readable.setEncoding('utf8'); readable.on('data', (chunk) => { console.log('got %d bytes of data', chunk.length, String(chunk)); }); readable.pipe(writable); ; read由开发人员实现,但不会被调用。希望这是正确的。我唯一的问题是为什么read没有在可写流中调用。我也很好奇为什么读取不接受回调。

相关问题