0

I'm using node/express and trying to follow the answers I see here: Display Pdf in browser using express js

but I'm not sure how to find the path to my PDF file. It's located in the main directory of the project folder, within a folder called "file," so I thought the path would just be

./file/myPDF.pdf

but I just get a "failed to load PDF document" regardless of the path I use.

Community
  • 1
  • 1
Jordan.B
  • 55
  • 6

2 Answers2

2

Using a relative path is not a good idea, NodeJS provide a "global" to build an absolute path:

var myPdf = require('path').normalize(__dirname + '/file/myPDF.pdf');
Shanoor
  • 13,344
  • 2
  • 29
  • 40
2

__dirname solves path problems in node.js. It is always the directory in which the currently executing script resides.

following is complete working code:

- files
     - my_pdf_file.pdf

app.js

var express = require('express'),
    fs = require('fs'),
    app = express();

app.get('/', function (req, res) {
    var filePath = "/files/my_pdf_file.pdf";

    fs.readFile(__dirname + filePath , function (err,data){
        res.contentType("application/pdf");
        res.send(data);
    });
});

app.listen(3000, function(){
    console.log('Listening on 3000');
});

for complete files and running project:

Clone node-cheat pdf_browser, run node app followed by npm install express.

Happy Helping!

Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57