如何将流转换为缓冲区?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (35)

如何在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!');
  });
});
提问于
用户回答回答于
var streamTo = require('stream-to');
req.form.on('part', function (part) {
  streamTo.buffer(part, function (err, buffer) {
    // Insert your business logic here
  });
});

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
});
用户回答回答于

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... }); });

扫码关注云+社区

领取腾讯云代金券