I have a problem with nodejs. Im now making a server that will serve the files requested by the users. What I did:
- I get the path
- find the file (
fs.exists()) - If the path is a file get the stream
- stream.pipe (response)
The problem now is that I want that the user download the file, but if I write a .txt file, the pipe method write the content of the file in the browser... So, I tried with a .pdf, but in this case the web page keep loading and nothing happen... Can someone help?
if(exists) {
response.writeHead(302, {"Content-type":'text/plain'});
var stat = fs.statSync(pathname);
if(stat.isFile()) {
var stream = fs.createReadStream(pathname);
stream.pipe(response);
} else {
response.writeHead(404, {"Content-type":'text/plain'});
response.end()
}
//response.end();
} else {
response.writeHead(404, {"Content-type":'text/plain'});
response.write("Not Found");
response.end()
}
2 Answers 2
Well, in your if case you always set the Content-Type header to text/plain, that's why your browser shows your text file inline. And for your PDF, text/plain is just the wrong one, it should be application/pdf, so you need to set the type dynamically.
If you want the browser to enforce a download, set the following headers:
Content-Disposition: attachment; filename="your filename..."
Content-Type: text/plain (or whatever your content-type is...)
Basically, this is what Express's res.download function does as well internally, so this function may be worth a look as well.
well, looks like the problem is that the pdf content type isnt text/plain.
Replace the content type to application/pdf
like:
response.writeHead(302, {"Content-type":'application/pdf'});
More info here: http://www.iana.org/assignments/media-types and http://www.rfc-editor.org/rfc/rfc3778.txt
express'ssendfile. It also does the content-type handling for you.