[英]How to limit flow between streams in NodeJS
如果您沒有正確處理數據,您將遇到 memory 泄漏問題,這就是您的情況。 這就是您看到該消息的原因。
這是一個小示例,展示了如何在流式傳輸數據時限制讀取並相應地處理寫入。
let fs = require('fs');
let readableStream = fs.createReadStream('./src/roughdata.json'); // Read from
let writableStream = fs.createWriteStream('./src/data.json'); // Write to
readableStream.setEncoding('utf8'); // setting character encoding
let chunk; // piece of data (size defined by byteSize)
let count = 0; // bytes counter
let byteSize = 10; // how many bytes to read on each pass while streaming the data
readableStream.on('readable', function () {
while ((chunk = readableStream.read(byteSize)) != null) {
writableStream.write(chunk);
count += byteSize; // increment the counter on each pass to calculate the size
}
});
readableStream.on('end', function () {
console.log(`${count} bytes data read and write is done!`)
});
好吧,長話短說,您需要注意解決此類問題的機制是backpressure
。 當您使用標准node
的pipe()
時,這不是問題。 我正在對多個流使用自定義扇出,因此它發生了
你可以在這里閱讀https://nodejs.org/en/docs/guides/backpressuring-in-streams/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.