Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Setup View Engine in Node.js ?

Improve Article
Save Article
Like Article
  • Difficulty Level : Expert
  • Last Updated : 27 Apr, 2020
Improve Article
Save Article
Like Article

View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with plain javascript.

Installation of ejs module:

  1. You can visit the link Install ejs module. You can install this package by using the following command.
    npm install ejs
  2. After installing multer you can check your ejs version in command prompt using the command.
    npm version ejs
  3. After that, you can just create a folder and add a file for example app.js, To run this file you need to run the following command.
    node app.js
  4. To setup view engine, you need the write this middleware in your index.js as follow:
    app.set('views', path.join(__dirname, 'views'))
    app.set('view engine', 'ejs')

    where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept.

  5. Now create a EJS file like Demo.ejs and put this file in views folder.

Filename: Demo.ejs

<!DOCTYPE html>
    <title>View Engine Demo</title>
  <!- For printing variable these
      tags are used: <%= %>  -->
  <h1> <%= title %> </h1>
  <!- For business logic these
      tags are used: <% %> -->
  <% if(true){ %>
      <h4>Greetings from geeksforgeeks</h4
  <% } %>

Filename: app.js

const express = require('express')
const path = require('path')
const app = express()
// View Engine Setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.get('/', function(req, res){
    // Rendering our web page i.e. Demo.ejs
    // and passing title variable through it
    res.render('Demo', {
        title: 'View Engine Demo'
app.listen(8080, function(error){
    if(error) throw error
    console.log("Server created Successfully")

Steps to run the program:

  1. The project structure will look like this:
    project structure
  2. Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:
    npm install ejs
    npm install express
  3. Run app.js file using below command:
    node app.js

    Output of above command

  4. Open browser and type this URL:
  5. Then you will see the Demo.ejs page as shown below:
    Ejs Demo Page

So this is how you can setup a view engine in node js. There are many other engines exist like Handlebars, Mustache, etc.

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!