【问题标题】:How to convert buffer to stream in Nodejs如何在Nodejs中将缓冲区转换为流
【发布时间】:2018-04-15 19:11:21
【问题描述】:

我遇到了在Nodejs中将缓冲区转换为流的问题。代码如下:

var fs = require('fs');
var b = Buffer([80,80,80,80]);
var readStream = fs.createReadStream({path:b});

代码引发异常:

TypeError: path must be a string or Buffer

但是 Nodejs 的文档说 Buffer 是可以被 fs.createReadStream() 接受的。

fs.createReadStream(path[, options])
路径 | |
选项 |

有人可以回答这个问题吗?非常感谢!

【问题讨论】:

标签: node.js buffer


【解决方案1】:

NodeJS 8+ 版本。 将缓冲区转换为流

const { Readable } = require('stream');

/**
 * @param binary Buffer
 * returns readableInstanceStream Readable
 */
function bufferToStream(binary) {

    const readableInstanceStream = new Readable({
      read() {
        this.push(binary);
        this.push(null);
      }
    });

    return readableInstanceStream;
}

【讨论】:

  • 您能否澄清一下,在这里添加this.push(null); 的原因是什么?如果我不添加它并仅使用this.push(binary); 会发生什么?谢谢。
  • @MikeB。将块作为 null 传递表示流的结束 (EOF),其行为与 readable.push(null) 相同,之后无法写入更多数据。 EOF 信号放在缓冲区的末尾,任何缓冲的数据仍将被刷新。
【解决方案2】:

节点 0.10 +

将缓冲区转换为流

var Readable = require('stream').Readable; 

function bufferToStream(buffer) { 
  var stream = new Readable();
  stream.push(buffer);
  stream.push(null);

  return stream;
}

【讨论】:

    【解决方案3】:
    const { Readable } = require('stream');
    
    class BufferStream extends Readable {
        constructor ( buffer ){
            super();
            this.buffer = buffer;
        }
    
        _read (){
            this.push( this.buffer );
            this.push( null );
        }
    }
    
    function bufferToStream( buffer ) {
        return new BufferStream( buffer );
    }
    
    

    【讨论】:

      【解决方案4】:

      我已经用功能风格重写了 Alex Dykyi 的解决方案:

      var Readable = require('stream').Readable;
      
      [file_buffer, null].reduce(
          (stream, data) => stream.push(data) && stream,
          new Readable()
      )
      

      【讨论】:

        猜你喜欢
        • 2023-03-02
        • 2021-10-29
        • 1970-01-01
        • 1970-01-01
        • 2020-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多