nodejs without template engines?

164 Views Asked by At

I just started learning backend development and I decided to start with node js. I figured out express js and routing a bit. This question came to my mind. Is there a way to send data directly to ready html files without using any Template Engine technology? Do we have to use Template Engine technology?

1

There are 1 best solutions below

3
Nishang Raiyani On

In Express.js, you can definitely send data directly to HTML files without using a template engine. While template engines like EJS, Handlebars, or Pug are commonly used to dynamically render HTML templates with data, you can also send raw HTML files with placeholders and replace those placeholders with data on the server side.


app.get('/', (req, res) => {
   const html = `
    <!DOCTYPE html>
    <html>
      <head>
        <title>My Website</title>
      </head>
      <body>
        <h1>Welcome</h1>
      </body>
    </html>
  `;
  res.send(html);
});

You can use the express.static middleware to serve static files, including HTML files. Here's how you can do it:

Create a folder called "public" in your project directory and place your HTML files inside it. For example, let's assume you have an HTML file called "index.html" inside the "public" folder.

Set up Express to serve static files from the "public" folder:

app.use(express.static('public'));