简化的构造函数API


在简单的情况下,不通过继承来构建流,现在会有一些额外的好处。

这可以通过传递适当的方法作为构造选项来实现:

例子:

Readable

  1. var readable = new stream.Readable({
  2. read: function (n) {
  3. // sets this._read under the hood
  4. // push data onto the read queue, passing null
  5. // will signal the end of the stream (EOF)
  6. this.push(chunk);
  7. }
  8. });

Writable

  1. var writable = new stream.Writable({
  2. write: function (chunk, encoding, next) {
  3. // sets this._write under the hood
  4. // An optional error can be passed as the first argument
  5. next()
  6. }
  7. });
  8. // or
  9. var writable = new stream.Writable({
  10. writev: function (chunks, next) {
  11. // sets this._writev under the hood
  12. // An optional error can be passed as the first argument
  13. next()
  14. }
  15. });

Duplex

  1. var duplex = new stream.Duplex({
  2. read: function (n) {
  3. // sets this._read under the hood
  4. // push data onto the read queue, passing null
  5. // will signal the end of the stream (EOF)
  6. this.push(chunk);
  7. },
  8. write: function (chunk, encoding, next) {
  9. // sets this._write under the hood
  10. // An optional error can be passed as the first argument
  11. next()
  12. }
  13. });
  14. // or
  15. var duplex = new stream.Duplex({
  16. read: function (n) {
  17. // sets this._read under the hood
  18. // push data onto the read queue, passing null
  19. // will signal the end of the stream (EOF)
  20. this.push(chunk);
  21. },
  22. writev: function (chunks, next) {
  23. // sets this._writev under the hood
  24. // An optional error can be passed as the first argument
  25. next()
  26. }
  27. });

Transform

  1. var transform = new stream.Transform({
  2. transform: function (chunk, encoding, next) {
  3. // sets this._transform under the hood
  4. // generate output as many times as needed
  5. // this.push(chunk);
  6. // call when the current chunk is consumed
  7. next();
  8. },
  9. flush: function (done) {
  10. // sets this._flush under the hood
  11. // generate output as many times as needed
  12. // this.push(chunk);
  13. done();
  14. }
  15. });