mpen
mpen

Reputation: 282805

How to abort a request?

I'm writing an upload script. If there's an error while writing to disk I want to abort the request and return a 500 status code.

My code (below) sends a 500 as expected, but the upload doesn't stop. I keep getting "data" events until the upload is complete (even though my write pipe is already broken) and then the req.on('end' event fires which tries to send a 204 even though I've already sent a 500.

How can I abort the request so that I stop getting event notifications?

var filename = req.headers['wx-filename'];
var docType = req.headers['wx-doc-type'];
var clientId = req.headers['wx-client-id'];

var dir = Path.join(config.storage_path, docType, clientId);
var filePath = Path.join(dir, filename);

mkdirp.sync(dir);

var destFile = FileSystem.createWriteStream(filePath, {
    flags: 'wx' // don't overwrite files
});

if (config.env === 'dev') {
    (function () {
        var fileSize = req.headers['content-length'];
        var uploadedBytes = 0;

        req.on('data', function (data) {
            uploadedBytes += data.length;
            var p = uploadedBytes / fileSize * 100;
            var fn = Path.relative(config.storage_path, filePath);
            util.log(fn + ': ' + p.toFixed(1) + '%');
        });
    })();
}

req.on('end', function () {
    util.log("END");
    resp.writeHead(204);
    resp.end();
});

destFile.on('error', function (err) {
    util.log("ERROR", err);
    resp.writeHead(500, err.code);
    resp.end();
    // HOW TO STOP REQUEST?
});

req.pipe(destFile);

Upvotes: 1

Views: 155

Answers (1)

Alexandru Guzinschi
Alexandru Guzinschi

Reputation: 5726

You need to remove the listeners for data and end, after that send a Connection: close header and at the end send the 500 error.

Upvotes: 2

Related Questions