How to Host a Static Webpage using Node.js

by Aug 1, 2022IoT Connectivity, IoT Continuous Integration

Introduction

In this tutorial, we will be discussing how to host a static webpage using Node.js. We will be hosting a simple HTML webpage on our first Node.js server. So let’s get started with the tutorial.

Downloading Node.js

The first step will be to download Node.js. You can visit the official website by clicking here.

So, after visiting the website, first, click on LTS option. This is the version that is most recommended for users, as it’s the most tested version of Node.js and is free of bugs. Next, we click on the Windows Installer for installing on a Windows device. If you have a Mac, you can use the macOS installer.

Once the installation is done, let’s start with creating our webserver.

Creating a Node.js web server

First, let us take a look at our file system.

File System
node Webserver
|
|--app.js
|--main.html

The file system consists of a JavaScript file for our node.js web server, and the HTML file that we are going to host. So first, let’s look at the contents of our HTML file. The code is as follows:

HTML Code

<html>
    <head>
        <title>Hello World</title>
    </head>
    <style>
        body{
            background-color: blanchedalmond;
        }
        .text{
            text-align: center;
            background-color: aliceblue;
        }
    </style>
    <body>
        <div class = "text">
            <h1>Hello World!</h1>
            <p>Your first node.js hosted website!</p>
        </div>
    </body>
</html>

This is our HTML code. It’s a basic webpage displaying Hello World! along with some text. We have also used some basic CSS for the background-colour, as well as for aligning the text to the center.

Next, let’s look at the contents of our JavaScript file. The complete code is as follows:

JavaScript code

const http = require('http')
const fs = require('fs')
const port = 3000

const server = http.createServer(function(req,res) {
    res.writeHead(200, {'Content-Type':'text/html'})
    fs.readFile('main.html', function(error, data){
        if(error){
            res.writeHead(404)
            res.write('Error: File not found')
        }else{
            res.write(data)
        }
        res.end()
    })

})

server.listen(port, function(error) {
    if (error) {
        console.log('An error has occured', error)

    } else {
        console.log('Server is running on port ' + port)
    }
})

require(‘http’): In order to transfer data over the Hyper Text Transfer Protocol (HTTP), we use the built-in “http” module of node.js. We can include it in our code using the require() function.

require(‘fs’): As we discussed earlier, we are using a file system with all the necessary files for hosting our webpage. In order to work with this file system, node.js provides us with an in-built file system module. We can include it by using the require(‘fs’) function.

Next, we declare the port number as 3000

Creating the HTTP Server

http.createServer(): Following this, we create a HTTP Server Object by using the function http.createServer(). Next, we give a function as the argument of the http.createServer() function. This function gets executed every time the server gets a request. Hence, this function is called the requestListener as it handles requests from users, as well as responds back to the user.

function(req,res) : The req object represents the HTTP request and the res object represents the HTTP response

res.writeHead(): This function sends a response header to the request. It takes a status code as the first argument. We give the status code 200 to indicate that the request has succeeded. Following this, we give {‘Content-Type’:’text/html’} as next argument. This is to indicate that the content is HTML.

fs.readFile(): This function is used to read the file. In our case, we need to read our HTML file. So we give the name of our HTML file as the first argument of the function. As the second argument, we give a function that has an error object and data object as its parameters. In case an error occurs, we use the status code 404 using the res.writeHead() function and display an error message using the res.write() function. In case of no error, we display the contents of the HTML page using res.write(data) function. Finally, we end the response process using res.end() function.

server.listen(): Using this function, we create a server that listens to a specific port. We use this function to test whether the server is working properly. We give the port number and an error function as the arguments. If an error occurs, the console will display the error message. If no error occurs, the console will display “Server is running on port 3000

Starting the node.js webserver

First, open the command prompt.

Next, change the directory to your file system. For this type in “cd” followed by the path of your file system as shown below:

After changing the directory, type “node” followed by the name of your JavaScript file as shown below:

Next, open a browser, preferably Google Chrome, and type in the URL section – http://localhost:3000

If your webpage appears, then the hosting has been successful.

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

What is Edge Intelligence: Architecture and Use Cases

What is Edge Intelligence: Architecture and Use Cases

Introduction With the latest advancements in AI technologies, we have noticed a significant increase in the deployment of AI-based applications and services in recent years. More recently, with the booming IoT industry in particular, billions of mobiles and IoT...

Apache Kafka vs Apache Spark : All you need to know

Apache Kafka vs Apache Spark : All you need to know

Introduction Due to the increase in the volume of data, the demand for Stream processing is on the rise. Just processing the data wouldn't be enough, it should be done quickly too so that organizations can react to changing market conditions on a real-time basis. This...

Creating a Multiplication Skill in Alexa using Python

Creating a Multiplication Skill in Alexa using Python

Introduction In this tutorial, we will be focusing on how to create a custom multiplication skill in Alexa using Python. If you're completely new to Alexa skills, you can get a brief idea about it by clicking here. Subsequently, we have posted regarding account...

Creating a Hello World Skill in Alexa using Python

Creating a Hello World Skill in Alexa using Python

Introduction In this tutorial, we will be focusing on how to create a Hello World Skill in Alexa Developer Console. This is the most basic skill, and it would give us an idea about Skill-building using Alexa's developer console. If you're completely new to Alexa, you...

Creating a custom Date-Time skill in Alexa using Python

Creating a custom Date-Time skill in Alexa using Python

Introduction In this tutorial, we will look at how to create a simple date-time skill in Alexa using Python. For this skill, the only prerequisites required are an Alexa developer account and some basic understanding of Python. Also, we have created a post on how to...

All you need to know about Amazon Alexa Skills

All you need to know about Amazon Alexa Skills

Introduction In this tutorial, we will be taking a quick look at Amazon Alexa Skills. So, let us get started with the most common question - What Is Amazon Alexa? Alexa is nothing but a cloud-based voice service provided by the tech giant Amazon. In today's world,...

Wi-Fi HaLow: IEEE 802.11ah Wireless Networking Protocol

Wi-Fi HaLow (pronounced "HEY-Low") is an IEEE 802.11ah wireless networking protocol. It was released in 2017 as an update to the IEEE 802.11-2007 wireless networking standard. It uses 900 MHz, license-exempt bands, to provide extended range Wi-Fi networks, as opposed...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....