如何将stream转换成nodejs中的缓冲区?这是我的代码解析一个文件在post请求在快递。
app.post('/upload',express.multipart({ defer: true }),function(req,res) { req.form.on('part',function(part) { //Here I want to convert the streaming part into a buffer. //do something buffer-specific task var out = fs.createWriteStream('image/' + part.filename); part.pipe(out); }); req.form.on('close',function() { res.send('uploaded!'); }); });
解决方法
您可以使用
stream-to
模块,它可以将可读流的数据转换为数组或缓冲区:
var streamTo = require('stream-to'); req.form.on('part',function (part) { streamTo.buffer(part,function (err,buffer) { // Insert your business logic here }); });
如果您希望更好地了解幕后发生的情况,您可以使用Writable
stream.自己实现逻辑。作为可写入流实现者,您只需定义一个函数:_write
method,每次有些数据将被调用写入流。当输入流完成发射数据时,将发出end
event:然后我们将使用Buffer.concat
method创建一个缓冲区。
var stream = require('stream'); var converter = new stream.Writable(); converter.data = []; // We'll store all the data inside this array converter._write = function (chunk) { this.data.push(chunk); }; converter.on('end',function() { // Will be emitted when the input stream has ended,ie. no more data will be provided var b = Buffer.concat(this.data); // Create a buffer from all the received chunks // Insert your business logic here });