使用节点js和express提供pdf文件

Bea*_*ast 5 pdf node.js express

所有PDF文件都保存在服务器上的文件系统中,如何使文件可以在客户端下载.

对于Ex:

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

是请求

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);
   }); 
}
Run Code Online (Sandbox Code Playgroud)

mok*_*oka 6

您可以express.static在应用中尽早使用,进行设置:

app.use('/pdf', express.static(__dirname + '/pathToPDF'));
Run Code Online (Sandbox Code Playgroud)

当浏览器导航到例如'/pdf/fooBar.pdf'时,它会自动为您完成工作.