title: File download from server in NodeJS
body: <p>I have my REST service in Java and it has a endpoint which sends a file to the client (HTTP GET, /file). My front end client is in NodeJS. I am not able to download the file from the REST service. I can only store the file at a particular location, but I want to have a download dialogue box where the user can store the file (just like any other download dialogue box). My NodeJS code is as below:</p>
  
  <pre><code>router.get('/openFile',function(req,res){
      native_data_retrieval_rest_client.get("http://localhost:8080/file?fileName=presentation.pcap",function(data){
          var fileName="/home/files/presentation.pcap";
          res.download(data);//This doesnt open dialogue box 
  
          fs.writeFile(fileName, data, function (err) {
              if (err) {
                  //Error handling
              } else {
                  console.log('Done');
              }
          });
      });
  });
  </code></pre>
  
  <p>The file is saved statically on the location <code>/home/files/presentation.pcap</code>.</p>
  
  <p>My REST service side response is like below:</p>
  
  <pre><code>response.setHeader("Content-Disposition", "attachment; filename="
                      + fileName);
              response.setHeader("Content-Type", type);
  
              reportBytes = new byte[131072];// New change
              OutputStream os = response.getOutputStream();// New change
              int read = 0;
              while ((read = inputStream.read(reportBytes)) != -1) {
                  os.write(reportBytes, 0, read);
              }
              //System.out.println("Bytes sent" + reportBytes);
              os.flush();
              os.close();
  </code></pre>
  
  <p>And the result which I get on the NodeJS side is just like an alert box with the file contents in it. See output below:</p>
  
  <p><a href="https://i.stack.imgur.com/SxcLE.png" rel="nofollow"><img src="https://i.stack.imgur.com/SxcLE.png" alt="enter image description here"></a></p>
  
  <p>Can anyone please let me know what mistake I am doing here. I would like to have download dialogue box when the user clicks on the Download button. When clicking the download button, a call should go to the REST service which in turn will send the file to the NodeJS front end and a dialogue box will open, which will ask the user for the location.</p>
  
  <p>My Call from HTML is like below </p>
  
  <pre><code>tr.append("td").append("button")
  .on("click", function(){
  
             openFile();
            })
  
   function openFile(){
            alert("button clicked");
  
            $http.get('/openFile/').success(function(response) {
                console.log(response.response);
             }).error(function(error){
                alert(error);
              });
  
            }
  </code></pre>