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!
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.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With