简体   繁体   中英

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!

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

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

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

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

  return stream;
}

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM