0

I am creating a node server to upload files using 'express','fs' and 'busboy' module. The server is working as expected but when I cancel the upload before complete, the incomplete file is stored in the filesystem. How can I remove the incomplete file?

var express = require("express"),
fs = require("fs"),
Busboy = require("busboy");
app = express();
app.listen(7000);
app.get("/", display_form);
app.post("/upload", function(req, res) {
var busboy = new Busboy({
    headers: req.headers
});
busboy.on("file", function(fieldname, file, filename, encoding, mime) {
    var fstream = fs.createWriteStream("./uploads/" + filename);
    file.pipe(fstream);
    file.on("data", function(chunk) {
        console.log(chunk.length);
    });
    file.on("end", function() {
        console("end");
    });

    fstream.on("close", function() {
        fstream.close();
        console("fstream close");
    });
    fstream.on("error", function() {
        console("fstream error ");
    });
});
busboy.on("finish", function() {
    console.log("uploaded");
    res.send("file uploaded");
});
busboy.on("error", function() {
    console("error busboy");
});
req.pipe(busboy);
});
Asis Datta
  • 561
  • 3
  • 11

2 Answers2

2

Thanks for your help and I finally I found a way to this problem. I added under mentioned code snippet and its working fine.

req.on("close", function(err) {
        fstream.end();
        fs.unlink('./uploads/' + name);
        console.log("req aborted by client");
    });
Asis Datta
  • 561
  • 3
  • 11
1

I don't know busboy, but you open a stream and never close it. Why don't you exploit the stream and filename to 'finish' and 'error' and act accordingly?

Example:

busboy.on('error', function() {
    fs.unlink('./uploads/' + filename);
    console.log('error busboy');
}
CFrei
  • 3,552
  • 1
  • 15
  • 29
  • Sorry, but if the upload completes then only I can get the control. In this case the control is going to none of the error handling block. – Asis Datta Sep 14 '14 at 05:18
  • If there is no way on server side to find out if the connection failed or canceled by the user, you can't determine if the upload is complete. Is there anything in the header that tells you how many bytes you should receive? So at `on.('close')` you could do a check. (Be aware that the counting depends heavily on the encoding.) – CFrei Sep 14 '14 at 09:20