将流转换为缓冲区?

时间:2013-11-11 12:33:30

标签: node.js

如何在nodejs中将流转换为缓冲区?这是我在快递中解析邮件请求中的文件的代码。

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!');
  });
});

2 个答案:

答案 0 :(得分:34)

您可以将dataend事件处理程序附加到part信息流来代替管道:

var buffers = [];
part.on('data', function(buffer) {
  buffers.push(buffer);
});
part.on('end', function() {
  var buffer = Buffer.concat(buffers);
  ...do your stuff...

  // write to file:
  fs.writeFile('image/' + part.filename, buffer, function(err) {
    // handle error, return response, etc...
  });
});

但是,将整个上传内容读入内存。如果这是一个问题,您可能需要考虑创建自定义transform stream来转换传入的数据,但这可能不是一件容易的事。

答案 1 :(得分:15)

您可以使用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
});