编辑:我在另一篇文章中解决了自己的问题:Extract binary values from stream with low memory consumption
如何精确控制NodeJS中的流的流量?
从快速路线中获取以下代码示例:
const stream = require('stream');
class ControlStream extends stream.Transform{
constructor(options){
super(options);
}
_transform(chunk, enc, callback){
this.push(chunk);
callback();
}
}
api.route("/stream").post((req, res) =>{
let controlStream = new ControlStream({});
req.pipe(controlStream);
});
在此示例中,我将请求流传递到ControlStream
实例中,该实例只是Transform
的子类。结果是数据连续流过ControlStream
。
我希望能够暂停此数据流,而能够“请求”每个数据块。
例如:
const stream = require('stream');
class ControlStream extends stream.Transform{
constructor(options){
super(options);
}
_transform(chunk, enc, callback){
this.push(chunk);
callback();
}
getChunk(){
//requests the next chunk of data to be sent into _transform
}
}
api.route("/stream").post((req, res) =>{
let controlStream = new ControlStream({});
req.pipe(controlStream);
controlStream.getChunk();
});
据我所知,默认实现只允许我“监听”数据流,但我似乎无法控制何时,或更重要的是,多少数据将流动。
感谢您的时间。
答案 0 :(得分:0)
https://nodejs.org/api/stream.html#stream_readable_pause
该组件的可读流组件确实具有暂停功能,该功能通过缓冲数据并停止任何(define (anti-omit-ref w l)
(implode (map (λ (x) (if (member? x (explode l)) x "_")) (explode w))))
事件来实现。
答案 1 :(得分:0)
由于express.Request
是ReadableStream
,那么异步迭代(for await
)又如何呢?
// your function
async function process(...args) {
//.....
}
// optional
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
api.route("/stream").post(async (req, res) => {
for await (const chunk of req) {
await process(chunk); // do something with the chunk
await sleep(3000); // you can also get a sleep if you need one
}
});
我不知道会有多少数据流