【发布时间】:2017-09-23 16:29:00
【问题描述】:
我正在尝试了解节点流及其生命周期。所以,我想将流的内容拆分为 n 部分。下面的代码只是为了解释我的意图并表明我已经自己尝试了一些东西。我省略了一些细节
我有一个流,它只生成一些数据(只是一个数字序列):
class Stream extends Readable {
constructor() {
super({objectMode: true, highWaterMark: 1})
this.counter = 0
}
_read(size) {
if(this.counter === 30) {
this.push(null)
} else {
this.push(this.counter)
}
this.counter += 1
}
}
const stream = new Stream()
stream.pause();
一个试图获取n个下一个块的函数:
function take(stream, count) {
const result = []
return new Promise(function(resolve) {
stream.once('readable', function() {
var chunk;
do {
chunk = stream.read()
if (_.isNull(chunk) || result.length > count) {
stream.pause()
break
}
result.push(chunk)
} while(true)
resolve(result)
})
})
}
并想像这样使用它:
take(stream, 3)
.then(res => {
assert.deepEqual(res, [1, 2, 3])
return take(stream, 3)
})
.then(res => {
assert.deepEqual(res, [4, 5, 6])
})
这样做的惯用方法是什么?
【问题讨论】:
标签: javascript node.js node.js-stream