Getting Started
Explore the process of creating a barebones Node.js app.
We'll cover the following
Our task
To really put our newly learned knowledge to test, we shall be creating a food delivery web application. Here are some of the goals we wish to accomplish:
- View all restaurants
- Choose items from a restaurant and add them to our cart
- Calculate a total for the cart and proceed to a checkout
Serving an HTML page
The simplest and easiest way to get started is to create a server. We have already seen how we can create a web server and display text using Node.js in a previous lesson. Now, we shall learn to serve web pages through our server, which is the foundation of our application.
We have created a simple HTML file in the same directory. We can use that page with Node.js using the fs
module. Let’s see how that might work.
const http = require('http'); const fs = require('fs') const hostname = '0.0.0.0'; const port = 3500; const homePage = fs.readFileSync('main.html') const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.write(homePage) res.end(); }); server.listen(port, hostname, () => { console.log('Server is now running'); });
We can use the command
npm start
in the root directory of our folder to run our application. However, since we are making changes or developing the application, we usenpm run dev
to run the development script.
Using the fs
module, we read our HTML page. We can then use the write()
method of the http.ServerResponse
class to write the HTML page as the response. You may notice that the images are not being displayed. This is because we are not reading the image files. We will fix this in the next demo.
Serving different pages
Let’s say we want to add an About page to our website so that new visitors can get to learn about our website. We also want to serve the images for each food type. However, we are just serving the main.html
page in the response. While we have ignored the req
or the request received by our server, it is now time to put it to use. The req
has a lot of properties, but the one we are looking for is the url
property. The url
property returns the URL that was received by the server. We can then use a simple if-else
condition to serve a different page based on the URL. Let’s take a look at that.
const http = require('http'); const fs = require('fs') const hostname = '0.0.0.0'; const port = 3500; const homePage = fs.readFileSync('main.html') const aboutPage = fs.readFileSync('about.html') const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); if (req.url == '/'){ res.write(homePage) } else if (req.url == '/about'){ res.write(aboutPage) }else if (req.url.match(/images/g)){ try{ res.statusCode = 200; res.setHeader("Content-Type", "image/jpeg"); imgLoc = req.url.replace('/', '../') image = fs.readFileSync(imgLoc) res.end(image); } catch { res.statusCode = 404; res.write("404"); console.log(req.url) } } else { res.write('404') } res.end(); }); server.listen(port, hostname, () => { console.log('Server is now running'); });
We added an additional About button to the hamburger menu in the top left that redirects to /about
, whereas the Food button redirects to /
. Changing the URL and our if-else
condition allows us to serve different pages. We have also fixed our images. Now, when the server receives a request for an image, it will read the corresponding image file and send it to the browser. Let’s see how we accomplished that.
- The
src
for theimg
tags in themain.html
file correspond to a path. Take a look at line 57 inmain.html
. - The image files are in the
image
folder for this course; however, you cannot see the folder. That folder exists in this project’s parent directory. - When the browser displays the HTML page, the
src
of allimg
tags are fetched. Since thesrc
are paths, the browser requests them from our Node.js server. - The request is sent to the server, with the request URL being the path for the image file. We use the
match
method and look for theimage
string in our URL in line 17. - If an image has been requested, we generate a response. We set the status code to
200
on line 19 and set the appropriate content type on line 20. - If the images folder was in the project directory, we would not need the code on line 21. Before we read the file, we need to change the path. We use the
replace
method to replace/
to../
. This will tell thereadFileSync
method to go to the parent directory. - Once we read the image file on line 22, we use the
end
method and pass it the image data to let it complete our response. Theend
method concludes the response from our server to the browser.
What if we had multiple pages instead of just two? Sure, we could use multiple if-else
conditions, but that is not only impractical but also looks messy.
Express to the rescue!
Express makes building web applications with Node.js much easier. It is a very popular and light-weight server-side framework. One of the reasons for its popularity is that it is written in JavaScript, so it ties well with the JavaScript Everywhere paradigm. We will use express in the complete version of the project in a later lesson.
Get hands-on with 1300+ tech skills courses.