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');
});Hit the RUN button to view the output
We can use the command
npm startin ...
Ask