简体   繁体   English

将流转换为缓冲区?

[英]Convert stream into buffer?

How to convert stream into buffer in nodejs? 如何在nodejs中将流转换为缓冲区? Here is my code to parse a file in post request in express. 这是我在快递中的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!');
  });
});

Instead of piping, you can attach data and end event handlers to the part stream to read it: 您可以将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...
  });
});

However, this will read the entire upload into memory. 但是,这读取整个上传到内存中。 If that's an issue, you might want to consider creating a custom transform stream to transform the incoming data, but that might not be trivial. 如果这是一个问题,您可能需要考虑创建自定义转换流来转换传入数据,但这可能不是一件容易的事。

You can use the stream-to module, which can convert a readable stream's data into an array or a buffer: 您可以使用stream-to模块,它可以将可读流的数据转换为数组或缓冲区:

var streamTo = require('stream-to');
req.form.on('part', function (part) {
  streamTo.buffer(part, function (err, buffer) {
    // Insert your business logic here
  });
});

If you want a better understanding of what's happening behind the scenes, you can implement the logic yourself, using a Writable stream . 如果您想更好地了解幕后发生的事情,可以使用Writable自己实现逻辑。 As a writable stream implementor, you only have to define one function: the _write method , that will be called every time some data is written to the stream. 作为可写流实现器,您只需要定义一个函数: _write方法 ,每次将某些数据写入流时都会调用该函数。 When the input stream is finished emitting data, the end event will be emitted: we'll then create a buffer using the Buffer.concat method . 当输入流完成发出数据时,将发出end事件 :然后我们将使用Buffer.concat方法创建一个缓冲区。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM