Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert buffer to stream in Nodejs

Tags:

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!

like image 990
zhangjpn Avatar asked Nov 03 '17 05:11

zhangjpn


People also ask

Is buffer a stream in node JS?

Buffer: In Node. js to manipulate a stream of binary data, the buffer module can be included in the code. However, the buffer is a global object in Node. js, hence it is not required to import it in code using the required method.

How do I use buffer and stream in node JS?

A buffer memory in Node by default works on String and Buffer . We can also make the buffer memory work on JavaScript objects. To do so, we need to set the property objectMode on the stream object to true . If we try to push some data into the stream, the data is pushed into the stream buffer.

How will you convert a buffer to JSON in node JS?

The Buffer. toJSON() method returns the buffer in JSON format. Note: The JSON. Stringify() is the method which can also be used to return the data in JSON format.

How do you convert a buffer to a string value in node JS?

Buffers have a toString() method that you can use to convert the buffer to a string. By default, toString() converts the buffer to a string using UTF8 encoding. For example, if you create a buffer from a string using Buffer. from() , the toString() function gives you the original string back.


1 Answers

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; } 
like image 168
аlex dykyі Avatar answered Oct 13 '22 20:10

аlex dykyі