NodeJS Setup With Express, HTML, CSS, JS & EJS

By Raddy in NodeJs ·

In this article, we will have a look at how to set up a NodeJS Server, we will cover Express, how to add CSS, JS and Images to your project and finally, we will look at how to use EJS. If you wish, you can also check out the video that I made.

So let’s get started.

Create a project folder

Name your project folder. This is where your project is going to live and all packages will be installed. Talking about packages, let’s go to step to and create our server setup.

Setup Server – Package.json file

This file is usually in the project root and it’s called package.json. It holds various metadata relevant to the project and it’s used to give information to npm that allows identifying the project as well as handle dependencies.

Go to the root of the folder, open PowerShell or the Termnal if you are using mac and type the following command.

npm init

As long as you have nodejs installed, this should guide you though the setup of your project. Once you finish with the installation, open your package.json file and just double check to see if everything is looking good.

Now let’s install some dependencies.

Install Dependencies

The dependencies we need to install to get started are Express and EJS.

Express is a web application framework for Node.js that is designed for building web applications and API’s.

EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. PUG is another good alternative that you can use.

So let’s install express and ejs together by running the following command:

npm install express ejs

Install Nodemon

Nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

To install nodemon simply do:

npm install nodemon --save-dev

Project Structure

Now let’s create the following folders and files, leaving node_modules, readme.md, package-lock and package-json as that should have been automatically generated by now.

πŸ“‚ node_modules
πŸ“‚ public
 πŸ“‚ css
  πŸ“œ main.css
 πŸ“‚ img
  πŸ–Ό cat.jpg
 πŸ“‚ js 
  πŸ“œ script.js
πŸ“‚ views
 🌍 about.js
 🌍 index.js
πŸ“œ README.md
🌍 app.js
πŸ“œ package-lock.json
πŸ“œ package-json

Run it

Before we run the project to see if everything is working as intended, we need to add some more metadata in our package.json file.

Open your package.json file and add the following under scripts

"start": "nodemon app.js"

Your full json file should look something like this:

{
  "name": "Learning NodeJS",
  "version": "1.0.0",
  "description": "NodeJS Tutorial",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.3",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.4"
  }
}

Save the file and now you should be able to run your project by simply doing:

npm start

We are getting close, but there are a few more things that we need to do before we are able to see our project. First, we need to add ‘express’ and select port number that NodeJs can listen on. Let’s do that.

In your app.js folder add the following code below and then run the project with “npm start”:

// Imports
const express = require('express')
const app = express()
const port = 5000

// Listen on Port 5000
app.listen(port, () => console.info(`App listening on port ${port}`))

Run your app, and see what happens. In PowerShell or Terminal (for Mac) you should see a message:

App listening on port 5000unless the port is already taken, then you can change it to 3000 or something like that.

Static Files

This will allow us to easily access our statics files such as css, js and images from our root folder of the project. Let’s have a look at how we can do that:

// Static Files
app.use(express.static('public'));
app.use('/css', express.static(__dirname + 'public/css'))
app.use('/js', express.static(__dirname + 'public/js'))
app.use('/img', express.static(__dirname + 'public/images'))

Setting up our View’s & EJS

This does two things. It will help us set up our views folder, where our html files will live and also we need to set the view engine which in our case is the EJS.

// Set View's
app.set('views', './views');
app.set('view engine', 'ejs');

Rendering Pages

In this example I will give you two options. One rendering the index.ejs file and one that simply grabs the about.html file.

// Navigation
app.get('', (req, res) => {
    res.render('index', { text: 'Hey' })
})

app.get('/about', (req, res) => {
   res.sendFile(__dirname + '/views/about.html')
})

Your final code for app.js should look something like this:

// Imports
const express = require('express')
const app = express()
const port = 5000

// Static Files
app.use(express.static('public'));
app.use('/css', express.static(__dirname + 'public/css'))
app.use('/js', express.static(__dirname + 'public/js'))
app.use('/img', express.static(__dirname + 'public/images'))

// Set View's
app.set('views', './views');
app.set('view engine', 'ejs');

// Navigation
app.get('', (req, res) => {
    res.render('index', { text: 'Hey' })
})

app.get('/about', (req, res) => {
   res.sendFile(__dirname + '/views/about.html')
})

app.listen(port, () => console.info(`App listening on port ${port}`))

Example of EJS page

For our index.html let’s see how we can add our stylesheet and also some EJS code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/main.css">
</head>
<body>
    
    Index baby
    <img src="img/cat.jpg" alt="cat">
    <h1><%= text %></h1>

</body>
</html>

Final

You should be able to run the project now by doing npm start and then open localhost:5000 to open the page in the browser. Of course if you want to visit the about page you should add slash after the url just like this localhost:5000/about

npm start

And that’s everything.

Credit: Cat image Photo by Ramiz Dedaković on Unsplash

  1. Muhammad hamza says:

    how to handle the js file which is in public folder

    1. Raddy says:

      You can include your js file in your HTML, in the head and start using it just like the styles (main.css)

Leave a Reply

Your email address will not be published. Required fields are marked *