我正在尝试通过流将变量添加到特定索引处的模板中。
我的想法是,我有一个可读流和一个变量列表,这些变量可以是可读流、缓冲区或不确定大小的字符串。这些变量可以插入到预定义的索引列表中。根据我的假设和迄今为止我所做的尝试,我有几个问题。
我的第一次尝试是使用可读流手动完成此操作。但是,在尝试读取它之前我无法const buffer = templateIn.read(size)(因为缓冲区仍然是空的) 。template combined该问题的解决方案与使用转换流的方式类似,因此这是我采取的下一步。
但是,我在转换流方面遇到问题。我的问题是,像这样的伪代码会将缓冲区堆积到内存中,直到done()被调用。
public _transform(chunk: Buffer, encoding: string, done: (err?: Error, data?: any) => void ): void {
let index = 0;
while (index < chunk.length) {
if (index === this.variableIndex) { // the basic idea (the actual logic is a bit more complex)
this.insertStreamHere(index);
index++;
} else {
// continue reading stream normally
}
}
done()
}
Run Code Online (Sandbox Code Playgroud)
来自: https: //github.com/nodejs/node/blob/master/lib/_stream_transform.js
在转换流中,写入的数据被放置在缓冲区中。当调用 _read(n) 时,它会转换排队的数据,在消耗块时调用缓冲的 _write cb。如果消耗单个写入块将导致多个输出块,则第一个输出位调用 readcb,后续块将进入读取缓冲区,并在必要时使其发出“可读”信号。
这样,背压实际上是由读取端决定的,因为必须调用 …
node.js ×1