Beast
Beast

Reputation: 615

serve pdf files using node js & express

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);
   }); 
}

Upvotes: 6

Views: 14374

Answers (1)

moka
moka

Reputation: 23047

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'.

Upvotes: 9

Related Questions