Home » Node.js

Developing a website using Node JS

In this article, we are going to build some real stuff. Here, we are developing a website using Node JS.
Submitted by Mansha Lamba, on October 20, 2018

You will have your own fully functional website running on "localhost" after going through this article.

Basic knowledge of JavaScript and HTML is a prerequisite.

Here are the source codes of the webpages...

JS file (a.js)

var http = require('http');

var fs = require('fs');

function notfoundfunc(response) {

    response.writeHead(404, {
        "Context-Type": "text/plain"
    });
    response.write("page not found");
    response.end();
}

function myfunc(request, response) {

    if (request.method == 'GET' && request.url == '/') {

        response.writeHead(200, {
            "Context-Type": "text/html"
        });
        fs.createReadStream("./index.html").pipe(response);

    } else if (request.method == 'GET' && request.url == '/about') {

        response.writeHead(200, {
            "Context-Type": "text/html"
        });
        fs.createReadStream("./about.html").pipe(response);

    } else {
        notfoundfunc(response);

    }
}

http.createServer(myfunc).listen(3500);
console.log("server made");

index.html

<html>

<body>

    welcome to my website.

</body>

</html>

about.html

<html>

<body>

    developed by mansha lamba.

</body>

</html>

Output screenshot 1

Develop a website in Node Js | Output file 1

Output screenshot 2

Develop a website in Node Js | Output file 2

Output screenshot 3

Develop a website in Node Js | Output file 3

Explanation of the code:

The source code is very easy to understand.

Please note that instead of giving a plain text output like in my previous article here I have used HTML files. For that, another inbuilt module in NODE JS is used i.e. fs.

Rest of the code is self-explanatory.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.