如何在Nodejs

时间:2017-11-03 05:48:13

标签: node.js buffer

我遇到了在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的文档说fs.createReadStream()可以接受缓冲区。

  

fs.createReadStream(path [,options])
    路径< string> | <缓冲液> | < URL>
    options< string> | <对象>

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

5 个答案:

答案 0 :(得分:4)

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;

  }

答案 1 :(得分:0)

节点0.10 +

将缓冲区转换为流

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

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

  return stream;
}

答案 2 :(得分:0)

我用功能样式重写了Alex Dykyi的解决方案:

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

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

答案 3 :(得分:0)

noexcept(true)

答案 4 :(得分:-3)

with hv as ( select hv.*, count(*) over (partition by address, appointment_date order by workno) as cnt from housevisits hv ) select hv.* from hv where cnt = 1; 旨在对文件系统执行操作 fs期望一个路径作为第一个参数,可以是文件名,文件的url或文件缓冲区(因为它很好地解释了here)。您正在传递对象fs.createReadStream()

如果您尝试使用{path:b}正确的语法,则错误会变得更加明确:

createReadStream()