0

For example:
1. Test1.txt Its base64:VGhpcyBpcyB0ZXN0MS4=
2. Test2.txt Its base64:VGhpcyBpcyBUZXN0Mi4=

My code:

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

output:

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=

Why is Data2 empty? How do I modify this code? Please Help! Thanks~

I tried to use Buffer.toString('base64') in file.event(data), but it can only convert text content, pictures can not be converted?

Nix
  • 5
  • 2
  • 6

1 Answers1

2

You don't need those extra streams. The problem though is that the extra streams' end events are emitted on the next tick (thus, after busboy's finish event).

You should be able to simplify your code to this:

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);
})
mscdex
  • 104,356
  • 15
  • 192
  • 153