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

问题描述 投票:0回答:4

我遇到了在 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(路径[,选项])
  路径 | |
  选项 |

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

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

将 chunk 作为 null 传递表示流的结束 (EOF),其行为与 Read.push(null) 相同,之后不能再写入任何数据。 EOF 信号被放置在缓冲区的末尾,任何缓冲的数据仍将被刷新

节点0.10+

将缓冲区转换为流

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

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

  return stream;
}
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 );
}

我用函数式风格重写了 Alex Dykyi 的解决方案:

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

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

node.js buffer
4个回答
51
投票

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

将 chunk 作为 null 传递表示流的结束 (EOF),其行为与 Read.push(null) 相同,之后不能再写入任何数据。 EOF 信号被放置在缓冲区的末尾,任何缓冲的数据仍将被刷新


19
投票

节点0.10+

将缓冲区转换为流

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()
)
© www.soinside.com 2019 - 2024. All rights reserved.