Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS: Serving dynamic files

I've been used to PHP, where code is put in a file, and executed each time on load.

With NodeJS, I need to use HTML files, but need calculation done within the files. A solution would be putting the whole file's HTML content into the file that is running the HTTP server, but I'd like to have them in files instead.

I am using NodeJS, and Express. How is this done?

like image 704
hexacyanide Avatar asked Aug 15 '26 00:08

hexacyanide


1 Answers

If you are using express and want to render HTML files you should use ejs as your template engine. Here is how you do it from scratch:

start a new project with express -e

tell express to use ejs for rendering HTML files:

app.configure(function(){
  // ... 
  app.set('views', __dirname + '/views');
  // app.set('view engine', 'ejs');
  app.engine('html', require('ejs').renderFile);
  // ...
});

create a route:

app.get("/", function(req, res) {
  res.render("your.html", {
    title: "This is plain HTML rendered with ejs"
  })
})

and finally your your.html file in the views folder

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
  </body>
</html>
like image 150
zemirco Avatar answered Aug 17 '26 17:08

zemirco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!