title: Nodejs download file error handling
body: <p>I can use nodejs to successfully download a file from server to client if everything is right. </p>
  
  <p>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?</p>
  
  <pre><code>//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);
  });
  </code></pre>