Home » Node.js

Hello World in Node, Express and EJS (1) | Introduction to EJS

In this tutorial, we are going to learn about the EJS (Embedded JavaScript) with example of Hello world in Node, Express and EJS (part 1).
Submitted by Godwill Tetah, on June 27, 2019

Hi! Welcome to NODE AND EJS TEMPLATE ENGINE SERIES. Today, we will write our first code in using EJS as template engine or view engine.

Take Note! You should have Node.js installed in your before you can start using EJS in this article.

To download Node JS, visit nodejs.org.

Then install.

* BASIC NODE.JS/EXPRESS KNOWLEDGE REQUIRED.

To begin, ensure you have EJS and express installed via npm.

To install EJS, simply open a terminal/command prompt and type the following command.

    npm install ejs
    or
    npm install ejs –save
EJS Image 1

You can use either command prompt or PowerShell as terminal.

We will create 2 files, one for our express server file and the second our EJS file.

Open your text editor and type the following code, Save as app.js.

var express = require ('express'); 
var app = express(); 
app.get ("/", function (req,res) {
	res.render ( "hello.ejs" );	
	} );
app.listen(3000 , function () {
	console.log ("server is listening!!!");
} );

Unlike any other express app, we used res.render then the ejs file and not res.send.

Also, I didn't require the ejs app. There's no problem!. You can do so if you wish.

Now, let's create our EJS file.

Open a text editor and type the following code, Save as hello.ejs

    <h1>Hello EJS World </h1>
  • Create a folder in your app.js directory called views.
  • Cut and paste the ejs file in the views folder.
  • Take Note: The folder name views are not a random word I selected but it's the reserved folder name where express checks for template engine by default.

Finally, initiate the app.js file and view the port in a browser, localhost:3000

EJS Image 2

Or for those using nodemon, use

EJS Image 3

EJS Image 4

There's yet another way to code hello world using EJS which will be disclosed in the next article.

Thanks for coding with me! Feel free to drop a comment or question.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.