Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js sendfile() vs. render()

I tried both res.render('index.html') and res.sendfile('index.html') and they both seem to be doing the same thing. I don't find the Express.js documentation very helpful.

What's the difference between the two?

like image 682
Soubriquet Avatar asked May 26 '14 17:05

Soubriquet


People also ask

What is Express sendFile?

The sendFile() Method. The Express framework provides a sendFile() method available on the response object which can be used to send static files to the client.

What is the difference between res render and RES redirect?

redirect('/home') (or whatever URL you want here) to tell the browser to go to the new URL. Browser processes the redirect and sends request for that new page. Server sees request for the new page and uses res. render() to render the data for that page.

What does sendFile return?

When sendfile() returns, this variable will be set to the offset of the byte following the last byte that was read. If offset is not NULL, then sendfile() does not modify the file offset of in_fd; otherwise the file offset is adjusted to reflect the number of bytes read from in_fd.

What does res render do?

The res. render() function is used to render a view and sends the rendered HTML string to the client.


1 Answers

The render method works when you have a templating engine, such as Handlebars or Jade, in use.

A templating engine is something that parses a given template file and generates HTML output. This is so you can generate an HTML web page depending on some variables in your program.

Such templates are often used with Express.js when writing applications that have a front-end.

The sendfile method, on the other hand, simply sends a given file to the client, regardless of the type and contents of the file.

Since you are using an HTML file, there is nothing particularly to be parsed by the templating engine. So, the output of render is same as that of sendfile (i.e., the HTML written in the file). Hence, both produce the same result.

like image 78
Chetan Bhasin Avatar answered Oct 06 '22 19:10

Chetan Bhasin