How to convert buffer to stream in Nodejs

早过忘川 提交于 2020-01-01 08:49:21

问题


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!


回答1:


fs is intended to perform operations on the file system.
fs.createReadStream() expect a path as it first argument which could be a file name, an url of a file or a file buffer (as it is nicely explained here). You are passing an object {path:b}.

If you try with the createReadStream() correct syntax, the error become more clear:

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

console.log(readStream);

// ReadStream {
//   ...
//   path: <Buffer 50 50 50 50>,
//   ...
// }
//
// Error: ENOENT: no such file or directory, open 'PPPP'



回答2:


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;

  }



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/47089230/how-to-convert-buffer-to-stream-in-nodejs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!