Express.js – app.render() Method


The app.render() method is used for returning the rendered HTML of a view using the callback function. This method accepts an optional parameter that is an object which contains the local variables for the view.

This method is similar to the res.render() function with the difference that it cannot send the rendered view to the client/user itself.


Syntax

app.render(view, [locals], callback)

Example

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

// app.render() 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 up the view engine
app.set('view engine', 'ejs');

// Rendering the email.ejs content from view
app.render('email', function (err, html) {
   if (err) console.log(err);
   console.log(html);
});

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

email.ejs

Now, create the file "email.ejs" and save it in the views folder.

<html>
<head>
   <title>Welcome to Tutorials Point</title>
</head>
<body>
   <h3>SIMPLY LEARNING</h3>
</body>
</html>

Output

C:\home
ode>> node appRender.js <html> <head> <title>Welcome to Tutorials Point</title> </head> <body> <h3>SIMPLY LEARNING</h3> </body> </html> Server listening on PORT 3000

Updated on: 30-Sep-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements