javascriptnode.jsfile-uploadbusboy

nodejs, connect-busboy. Upload few files


I have trouble with events when upload few files through busboy. My code:

app.post('/multiupload', function(req, res) {
    var fstream;
    var files = [];
    var busboy = new Busboy({headers: req.headers});
    busboy.on('file', function (fieldname, file, filename) {
        fstream = fs.createWriteStream(__dirname + '/../static/uploaded/' + filename);
        file.pipe(fstream);
        fstream.on('close', function(){
            console.log('file ' + filename + ' uploaded');
            files.push(filename);
        });
    });

    busboy.on('end', function(){console.log('END')});

    busboy.on('finish', function(){
        console.log('finish, files uploaded ', files);
        res.redirect('back');
    });
    req.pipe(busboy);
});

My form (Jade template)

form(method="POST", action="/multiupload" name="multiupload_form", enctype="multipart/form-data")
input(type='file' name='multifile', multiple)
input(type="submit" value="Upload!")

Event 'end' just ignored, finish fire in middle of files uploading. Where i wrong?

Server console report:

file 111.gz uploaded
file 222.mp4 uploaded
file 333.jpg uploaded
finish, files uploaded  [ '111.gz', '222.mp4', '333.jpg' ]
file 444 uploaded
file 555.jpg uploaded

Solution

  • busboy does not emit an end event. The finish event is emitted once the entire request has been processed and all file streams have been completely read. So the problem is that the closing of the underlying file descriptor happens in the next tick (or so) which happens after finish is emitted.

    If you need to know when all of the file descriptors are closed, then you will need to come up with a way of tracking how many close events have emitted.