Basic Node.js Server.

Table of contents

No heading

No headings in the article.

Welcome to my blog about Basic Node.js Server! Here, I will be sharing how I build a basic Node.js server, which just reads the HTML file with the help of a Node.js library called "fs"(file system). Let's get started!

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('index.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('spmething went wrong',error)
    }else{
        console.log('server is listening' + port)
    }
})

As we can see our server is listening at port 3000. it just runs a locally hosted server to render the HTML file we connected to the server.

let's understand the written code:-

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

These three lines are just library Importing at a variable name, you can change the names according to your preference. I prefer them because it makes the process less confusing and no problem of remembering the variable names assigned.

const server=http.createServer(function(req,res){
    res.writeHead(200,{'Content-Type':'text/html'})

    fs.readFile('index.html',function(error,data){
        if(error){
            res.writeHead(404)
            res.write('Error: File Not Found')
        }else{
            res.write(data);
        }
        res.end()

    })

})

These few lines are the main body which is written for reading the data of the HTML page.

  • 1st line- Just a function starting point which is assigned to the a variable called server

  • 2nd line- this line tells browser which type of file we will be sending.

  • 3rd line-From this line reading of that particular file starts and ends at res.end(most obvious).

server.listen(port,function(error){
    if(error){
        console.log('spmething went wrong',error)
    }else{
        console.log('server is listening' + port)
    }
})

This chunk of code is for the server listening, I mean it is telling the server to run at that particular port and some error handling is also there.

<!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>Document</title>
</head>
<body>
    <h1>Basic Node.js Server.</h1>
</body>
</html>

The HTML file we used is this one above.