本文介绍了Node.js 可读流 _read 用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解如何在 Node 的新 Streams2 库中使用可写流,但我不了解如何使用可读流.

I understand how to use writable streams in Node's new Streams2 library, but I don't understand how to use readable streams.

以一个围绕 dgram 模块的流包装器为例:

Take, for example, a stream wrapper around the dgram module:

var dgram = require('dgram');

var thumbs = {
  twiddle: function() {}
};

var defaults = {
  address: '0.0.0.0',
  type: 'udp4',
  port: 12345,
  broadcast: null,
  multicast: null,
  multicastTTL: 1
};

var UDPStream = function(options) {
  if (!(this instanceof UDPStream))
    return new UDPStream(options);

  Duplex.call(this);

  options = options || {};

  this.address = options.address || defaults.address;
  this.type = options.type || defaults.type;
  this.port = options.port || defaults.port;
  this.broadcast = options.broadcast || defaults.broadcast;
  this.multicast = options.multicast || defaults.multicast;
  this.multicastTTL = options.multicastTTL || defaults.multicastTTL;

  this._socket = dgram.createSocket(this.type, setup.bind(this));
  this._socket.on('message', this.push.bind(this));
};

util.inherits(UDPStream, Duplex);

var setup = function() {
  if (this.multicast) {
    this._socket.addMembership(this.multicast);
    this._socket.setMulticastTTL(this.multicastTTL);

    this.destination = this.multicast;
  } else {
    // default to using broadcast if multicast address is not specified.
    this._socket.setBroadcast(true);

    // TODO: get the default broadcast address from os.networkInterfaces() (not currently returned)
    this.destination = this.broadcast || '255.255.255.255';
  }
};

UDPStream.prototype._read = function(size) {
  thumbs.twiddle();
};

UDPStream.prototype._write = function(chunk, encoding, callback) {
  this._socket.send(chunk, 0, chunk.length, this.port, this.destination);
  callback();
};

module.exports = UDPStream;

除了 _read 实现之外,一切都有意义.这实际上是在摆弄拇指,因为我不明白我应该在那里做什么.我的数据在 udp 套接字发出新消息时被推送,但我无法暂停或恢复底层资源.应该是什么样子的?

Everything makes sense except for the _read implementation. It's literally twiddling thumbs because I don't understand what I'm supposed to do there. My data is pushed when the udp socket emits a new message, but I have no way of pausing or resuming the underlying resource. What should this look like?

推荐答案

答案很简单:如果真的没有办法对底层资源应用背压,那么你的 _read 实现就是空的.流将负责对推送的数据进行排队,直到它到达 highWaterMark,但不保证超出该点.文档 说你应该简单地提供随时可用的数据."

The answer is fairly straightforward: if there is truly no way to apply backpressure to your underlying resource, your _read implementation is simply empty. The stream will take care of queueing your pushed data until it hits the highWaterMark, but guarantees nothing beyond that point. The docs say that you should "simply provide data whenever it becomes available."

这篇关于Node.js 可读流 _read 用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 11:22