How to call Node JS function from EJS

In this tutorial, you will learn how to call a function in your Node JS server file from the EJS template file.

First, we are going to install all the required modules. Run the following commands in your terminal:

> npm install http express ejs
> npm install -g nodemon
> nodemon server.js

Then, create a file named server.js and write the following code in it.

const app = require("express")()
const http = require("http").createServer(app)
const ejs = require("ejs")
app.set("view engine", "ejs")

const port = process.env.PORT || 3000
http.listen(port, function () {
    app.get("/", async function (request, result) {
        const html = await ejs.renderFile("views/index.ejs", null, {
            async: true
        })

        result.send(html)
        return
    })
})

Then, create a folder named views and inside this folder, create a file named index.ejs

To call a function from EJS file, we will first create a helper module in our server file. Create a file named helper.js at the root of your project. Following code will go in this file:

module.exports = {
	myFunc() {
		return "My function value."
	}
}

Then, include this module in your server.js file.

const helper = require("./helper")

And pass it in your renderFile function like this:

const html = await ejs.renderFile("views/index.ejs", {
    helper: helper
}, {
    async: true
})

Now you can easily call it from your index.ejs in the following way:

<%= helper.myFunc() %>

Since you are rendering the EJS file using await command, if you have to include another EJS file, you have to include it using await as well.

<%- await include ("header") %>

So that’s how you can call function in Node JS server file from your EJS template file. If you face any problem in following this, kindly do let me know.