1. Download and Install NodeJS
You can go to https://nodejs.org/ page. There will be two versions available to download on the home page. Better to download LTS version and install it in your machine.
2. Create a new NodeJS project
First create a new folder and open the folder location in your command prompt (CMD) or in terminal and enter npm init -y
. It will create a new package.json file inside your newly created folder.
3. Write your first node program.
Create two new files as app.js and write the below code.
const http = require('http');
const server = http.createServer((req, res) => {
console.log(req);
});
server.listen(3000);
In the first line, we are importing the http
from the NodeJS core module.
http.createServer
creates a new server and it have 2 Request Listeners. req
is for Incoming Message and res
is for Server Response. When the server starts, we are logging the req
data in the console.
server.listen(3000)
it will run the node application in the port 3000
Let’s run this app. Open your CMD or terminal and run node app.js
and open http://localhost:3000
in your browser. For now, you won’t see any data on the browser. But in the console you can see the request object like headers, httpVersion, host, url method and more.
To stop this server, open your CMD and click ctrl + c
. It will stop your local server.
4. Sending HTML Response
Now create a new app.html file and write the below code.
<!-- app.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Page</title>
</head>
<body>
<h1>Hello from the Node.js Server!</h1>
</body>
</html>
In the app.js file, import fs
// app.js
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.write(fs.readFileSync('./app.html'))
res.end();
});
server.listen(3000);
fs
is for reading and writing a file. 'Content-Type, 'text/html'
will set the response content type as text/html.
res.write(fs.readFileSync('.app.html');
will read the app.hmtl
file content and writes in the response.
Now run the application with node app.js
command and open http://localhost:3000 in your browser. There you have to see your HTML content in the browser.
5. Routing
Let’s create routing for the node.js application.
// app.js
const server = http.createServer((req, res) => {
const url = req.url;
if (url == '/') {
res.write(fs.readFileSync('./app.html'));
} if (url == '/about') {
res.write(`
<html>
<head><title>About Page</title></head>
<body>
<h1>About Page !!</h1>
</body>
</html>
`);
}
res.end();
});
In the req.url
you will find the URL. If the route is '/'
it is default root page. Now open https://localhost:3000/about in your browser. The req.url
value will be '/about'
. So, content in the HTML page you will see About Page HTML.