如何在 node.js 流中等待一些固定数量的字节? [英] How to wait for some fixed amount of bytes in a node.js stream?
问题描述
我有一个 node.js 可读流,我想读取前 20 个字节并对其进行一些处理,为处理后的数据设置回调或接收承诺.
I have a node.js Readable stream and I want to read the first 20 bytes and do some processing with them, setting a callback for the processed data or receiving a promise.
节点或 NPM 中的其他地方是否有任何内置函数可以做到这一点?
Is there any function built in node or elsewhere in NPM to do that?
例如,它可能看起来像这样:
For example, it could look something like this:
var stream = getStreamSomehow();
readPromise(stream, 20)
.then(function(data) {
console.log("I have read 20 bytes! %s", data.toString());
});
推荐答案
使用 node core 执行此操作的典型方法是调用 stream.read(20)
,检查返回值是否为 null
如果是这样,请在再次尝试 stream.read(20)
之前侦听 readable
事件.否则,如果返回值不为 null,则它是一个 20 字节的缓冲区,其中包含来自流的数据.
The typical way to do this with node core is by calling stream.read(20)
, checking if the return value is null
and if so, listen for the readable
event before trying to stream.read(20)
again. Otherwise if the return is not null, it's a 20-byte Buffer containing data from the stream.
这篇关于如何在 node.js 流中等待一些固定数量的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!