zhangjpn
zhangjpn

Reputation: 355

How to convert buffer to stream in Nodejs

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!

Upvotes: 30

Views: 55495

Answers (4)

аlex
аlex

Reputation: 5698

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

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

Upvotes: 51

Roy Jang
Roy Jang

Reputation: 21

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

Upvotes: 2

spirinvladimir
spirinvladimir

Reputation: 688

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()
)

Upvotes: -6

аlex
аlex

Reputation: 5698

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

Upvotes: 19

Related Questions