1

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()
}
cr0
6175 silver badges17 bronze badges
asked Oct 25, 2013 at 12:52
2
  • 1
    welcome, you should add the code. then SO can help you. thanks Commented Oct 25, 2013 at 12:54
  • 1
    Have a look at express's sendfile. It also does the content-type handling for you. Commented Oct 25, 2013 at 13:08

2 Answers 2

1

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.

answered Oct 25, 2013 at 13:09
Sign up to request clarification or add additional context in comments.

2 Comments

Nice it works, thank you. But I cant use setHeader and the write the header right?
I mean, can you specify that when you do response.writeHeader()?
1

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

answered Oct 25, 2013 at 13:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.