在busboy.event(完成)我无法获得file.pipe.object结果

时间:2015-07-02 15:20:09

标签: node.js busboy

例如:
1. Test1.txt其base64:VGhpcyBpcyB0ZXN0MS4 =
2. Test2.txt其base64:VGhpcyBpcyBUZXN0Mi4 =

我的代码:

var busboy = new Busboy({ headers: req.headers });
var base64data = [];
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    var output = stream.PassThrough();
    var chunk = [];
    console.log('File: ' + filename + ', mimetype: ' + mimetype);
    file.pipe(base64.encode()).pipe(output);
    output.on('data', function(data) {
        chunk.push(data);
        console.log('Chunk: ' + chunk);
    });
    output.on('end', function(){
        base64data.push(Buffer.concat(chunk));
        console.log('Data1: ' + base64data);
    });
}).on('finish', function(){
    console.log('Data2: ' + base64data);
})

输出:

File: Test1.txt, mimetype: text/plain
File: Test2.txt, mimetype: text/plain
Chunk: VGhpcyBpcyB0ZXN0
Chunk: VGhpcyBpcyBUZXN0
Chunk: VGhpcyBpcyB0ZXN0,MS4=
Chunk: VGhpcyBpcyBUZXN0,Mi4=
Data2:
Data1: VGhpcyBpcyB0ZXN0MS4=
Data1: VGhpcyBpcyB0ZXN0MS4=,VGhpcyBpcyBUZXN0Mi4=

为什么Data2为空?如何修改此代码?请帮忙!感谢〜

我尝试在file.event(data)中使用Buffer.toString('base64'),但它只能转换文本内容,图片无法转换?

1 个答案:

答案 0 :(得分:2)

您不需要那些额外的流。但问题是额外的流'end事件是在下一个tick上发出的(因此,在busboy的finish事件之后)。

您应该可以将代码简化为:

var busboy = new Busboy({ headers: req.headers });
var base64data = [];
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
  console.log('File: ' + filename + ', mimetype: ' + mimetype);
  var buffer = '';
  file.setEncoding('base64');
  file.on('data', function(data) {
    // `data` is now a base64-encoded chunk of file data
    buffer += data;
  }).on('end', function() {
    base64data.push(buffer);
  });
}).on('finish', function(){
  console.log('Data2: ' + base64data);
})