Skip to main content Skip to docs navigation
View on GitHub

Create a Node.js App with Express


Suraj Vishwakarma 02-02-2021

Use Express and EJS to render a website.

Express makes it much simpler to create a server and render different routes. Alongside EJS it makes web development a breeze. Express handles files, routing, parsing, and much more.

First, set up the Node.js project with npm init, or copy the package.json file provided at the end of the article. Then, run npm install to install the dependencies in the package.json file. In the app.js file, import express to start setting up the server and the routes.

const express = require('express')
const app = express()

You also need to set up EJS as a template engine, and link to the views folder to let express know where the view templates are located.

app.set('view engine', 'ejs')
app.set('views', 'views')

A simple way of setting up a route is using app.get() for GET requests.

app.get("/", (req, res) => {

Finally, set up the server on port 3000.


Now you can go to localhost:3000 and see the result. The second route should be located at localhost:3000/ejs.
Main source code now you need to create a file with the extension .js ie (server.js or index.js)

The folder structure of the project 





Complete Source Code: create file name with server.js

const express = require('express');
const app = express();
const path = require('path');

// for our public data like images and all
app.use(express.static(path.join(__dirname, 'public')));

//for setup view engine
app.set('view engine', 'ejs')
app.set('views', 'views')

app.get('/', (req, res) => {

app.listen(3000, () => {
  console.log('listening on *:3000');

view page in side views dir /  folder 

// views/index.ejs
<h1>Welcome to kodingnodes</h1>

After setup, you need to install nodejs package in your application follow the bellow commands for installing packages 

npm init (HIT ENTER)
npm install express (HIT ENTER)
npm install express (HIT ENTER)

after installing node modules run your node application by using 

node server