Tianyun Ling
Tianyun Ling

Reputation: 1097

Nodejs download file error handling

I can use nodejs to successfully download a file from server to client if everything is right.

But if error happens, I want to just return the error message. But what I now get is a downloaded file abc.txt which contains the error json. How to fix this?

//server side code, get like /download?filename=abc.txt
app.get('/download', function(req, res){

    var filename_para = req.query.filename; // abc.txt

    if( filename_para == undefined)
    {
        console.log('no filename provided');    
        res.send('no filename provided');// this works
        return;
    }

    var file = __dirname + '/uploads/' + filename_para;

    var filename = path.basename(file);
    var mimetype = mime.lookup(file);

    res.setHeader('Content-disposition', 'attachment; filename=' + filename);
    res.setHeader('Content-type', mimetype);

    var filestream = fs.createReadStream(file);

    filestream.on('error', function(err) {
         console.log('error '+err); 
        // filestream.close();
        res.send(err);// this error is in abc.txt???

    });

    filestream.on('finish', function() {
        console.log('finish');  
    });


    filestream.pipe(res);
});

Upvotes: 1

Views: 1408

Answers (1)

Robbie
Robbie

Reputation: 19510

You've already set the content-type and content-disposition headers on the response object. If you want to return the err as json, then remove the content-disposition header and set the content-type to application/json before calling res.send(err);

Upvotes: 2

Related Questions