Express.js – app.engine() Method


The app.engine() method is used for registering the given template engine callback as "ext". The require() method needs the engine based on the function by default.

Use the following methods for engines that do not provide the extensions (or want to map different extensions) or express out of the box.

app.engine('html', require('ejs').renderFile)

Syntax

app.engine(ext, callback)

Example 1

Create a file with the name "appEngine.js" and copy the following code snippet. After creating the file, use the command "node appEngine.js" to run this code.

// app.engine() Method Demo Example

// Importing the express module
const express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Setting the html page from view
app.engine('html', require('ejs').renderFile);

// Defining an endpoint to retrieve html page
app.get('/api', function (req, res) {
   res.render("api.html")
});

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

api.html

<html>
<head>
<title>app.engine() Demo Example</title>
</head>
<body>
   <h2>Welcome to Tutorials Point</h2>
</body>
</html>

Now, hit the following Endpoint on your browser

http://localhost:3000/api

Output

C:\home
ode>> node appEngine.js Server listening on PORT 3000

On the browser, you will get to see the following screen

Updated on: 30-Sep-2021

453 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements