如何在Nodejs中将缓冲区转换为流

30

我遇到了一个在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

然而,Node.js的文档指出Buffer可被fs.createReadStream()接受。

fs.createReadStream(path[, options])
  path <string> | <Buffer> | <URL>
  options <string> | <Object>

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


可能有重复 - Vikash Dahiya
谢谢,这正是我要找的! - zhangjpn
4个回答

49

将NodeJS 8+版本中的Buffer转换为Stream

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;
}

6
请问,加入 this.push(null); 的原因是什么?如果只使用 this.push(binary); 而不加入它会发生什么?谢谢。若不添加 this.push(null);,则流将不会标记为已完成,可能导致某些消费端无法正确处理流结束的事件。 - Mike
3
将chunk参数传入null表示数据流的结尾(EOF),并且与readable.push(null)相同,之后将无法再写入更多数据。EOF信号被放置在缓冲区末尾,任何已缓冲的数据仍将被刷新。 - аlex

18

将缓冲区(Buffer)转换为流(Stream)

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

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

  return stream;
}

2
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 );
}


-6

我已经按照Alex Dykyi的解决方案,以函数式风格进行了重写:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接