问题
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