30

I confront with a problem about converting buffer into stream in Nodejs.Here is the code:

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

The code raise an exception:

TypeError: path must be a string or Buffer

However the document of Nodejs says that Buffer is acceptable by fs.createReadStream().

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

Anybody could answer the question? Thanks very much!

zhangjpn
  • 355
  • 1
  • 3
  • 6

4 Answers4

48

NodeJS 8+ ver. convert Buffer to 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;
}
Mike
  • 14,010
  • 29
  • 101
  • 161
аlex
  • 5,426
  • 1
  • 29
  • 38
  • 6
    Could you please clarify, what is the reason to add `this.push(null);` here? What happens if I don't add it and stay with `this.push(binary);` only? Thanks. – Mike Jul 05 '20 at 08:59
  • 3
    @MikeB. Passing chunk as null signals the end of the stream (EOF) and behaves the same as readable.push(null), after which no more data can be written. The EOF signal is put at the end of the buffer and any buffered data will still be flushed. – аlex Aug 26 '20 at 15:38
18

Node 0.10 +

convert Buffer to Stream

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

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

  return stream;
}
аlex
  • 5,426
  • 1
  • 29
  • 38
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 );
}

Roy Jang
  • 21
  • 2
-6

I have rewritten solution from Alex Dykyi in functional style:

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

[file_buffer, null].reduce(
    (stream, data) => stream.push(data) && stream,
    new Readable()
)
spirinvladimir
  • 688
  • 7
  • 9