How to Setup View Engine in Node.js ?
Installation of ejs module:
- You can visit the link Install ejs module. You can install this package by using the following command.
npm install ejs
- After installing multer you can check your ejs version in command prompt using the command.
npm version ejs
- 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.
- 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.
- Now create a EJS file like Demo.ejs and put this file in views folder.
Steps to run the program:
- The project structure will look like this:
- 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
- Run app.js file using below command:
- Open browser and type this URL:
- Then you will see the Demo.ejs page as shown below:
So this is how you can setup a view engine in node js. There are many other engines exist like Handlebars, Mustache, etc.