6

All the PDF files are saved in the filesystem on the server, how to make the files to be downloadable in client side.

for Ex :

 app.use('/pdfDownload', function(req, res){
  var pathToTheFile = req.body.fileName;
   readFile(pathToTheFile, function(data){
      //code to make the data to be downloadable;
    });
 });

is the request made

function readFile(pathToTheFile, cb){
   var fs = require('fs');
   fs.readFile(pathToTheFile, function(err, data){
      //how to make the file fetched to be downloadable in the client requested
      //cb(data);
   }); 
}
Beast
  • 617
  • 2
  • 8
  • 19

1 Answers1

8

You can use express.static, set it up early in your app:

app.use('/pdf', express.static(__dirname + '/pathToPDF'));

And it will automatically do the job for you when browser navigates to e.g. '/pdf/fooBar.pdf'.

moka
  • 22,846
  • 4
  • 51
  • 67
  • @Makisms but what about the 'pathToTheFile' it'll be retrieved using the req object – Beast Jul 24 '13 at 11:29
  • Static will resolve it automatically. So if you go to `/pdf/test.pdf` then it will try to find file `/pathToPDF/test.pdf`. – moka Jul 24 '13 at 11:43
  • sorry bro i couldn't get you, If all the files are in /tmp/files/pdf directory. And the filename in the req is like ObjectId.pdf how will it flow ? could you please explain thanks – Beast Jul 24 '13 at 11:46
  • I understood you're comment, i think i'm doing a wrong request from clien side `$.get('/pathToPDF/fileName.pdf', function(data){ });` is it correct ? – Beast Jul 24 '13 at 12:02
  • You want to open PDF as new tab? Or what you want to get on client side? As well if all files are in /tmp/files/pdf, then you need to do: `app.use('/pdf', express.static('/tmp/files/pdf'));`. Express will resolve the end of url and will get the right file. Just set up express, and then try to navigate in browser to pdf file. – moka Jul 24 '13 at 13:57
  • Thanks man, that helped allot i was getting confused. i wanted to open pdf in new tab, achieved it using tag and href attribute was the url to the file. – Beast Jul 25 '13 at 08:56
  • Yep, that is a straight forward solution. If you need to open pdf using JS, do same but use `window.open`. – moka Jul 25 '13 at 09:38