Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You shall write a very basic web server in Javascript that will run via nodejs.

ID: 3825218 • Letter: Y

Question

You shall write a very basic web server in Javascript that will run via nodejs.

Your project shall include the following line: var paul   = require('/homes/paul/HTML/CS316/p3_req.js');

Your project will accept HTTP requests via URLs in the following format:

      /[a-zA-Z0-9_]*.cgi

Here are the steps you must perform for .cgi URLs: 1) call http .createserver(myprocess) my process() is a function you will write to process requests from the user via their browser 2) create a mylisten() function that takes the following parameters: 1) the http object returned in step one 2) a port number which is a random port number between paul.pstart() and paul. pend() 3) paul. .phost() 4) paul logger 3) myy listen() will call the 4th argument passing it 2 & 3 (the port and hostname) my listen will then call listen() on the 1st argument passing it arguments 2 3 also 4) my process accepts two parameters, request and response Your program needs to process request.url and fill in the appropriate values f response statusCode response.setHeader, and finally sending content via response.end(); 5) You will want to use fs.existsSync to verify if a requested file exists E) You will want to fs.readFilesync to read the HTML files 7) You MUST use child process.exec() You shall send it (3) parameters, the path of the program to execute (you can prepend it with the directory name specified above), and options parameter, and a callback function. the options parameter looks like this tenv: ourEnv) where ourEnv is declared like: var ourEnv t 'PATH XXoxx where xxxxxx is the directory given above "./MYCGI/", which is a subdirectory of the directory your server program resides. Note: this is a hardcoded, relative PATH. The PHP part uses a variable PATH that happens to be absolute. Keep the differences in mind. Remember, the options parameter is a array of arrays. env is one element of the array (the only one we're using for this assignment) The callback function is sent 3 parameters, error denoting an error condition and stdout and stderr streams All output from a successful run are contained in stdout and stderr You can simply concatenate them together The output (either an error message, or the combined stdout/stderr streams) should be returned to the requester As a security measure, you must provide exec() the environment object as above! 8) You shall have three functions, one to handle files one to handle CGI and one to handle PHP requests my process() should call them as appropriate. Do not put everything into myprocess Compartmentalize

Explanation / Answer

Node is a fantastic candidate for creating web servers; which are lightweight and can handle a great number of simultaneous requests. This means if you’re interested in learning to build scalable web applications this is a great beginner's guide.

Node.js is shipped with several core modules out of the box, which we will be using to set up our own http server. The http module makes it simple to create an http server via its simple but powerful api. Lets create an empty file named myFirstHTTPServer.js and write the following code into it:

//Lets require/import the HTTP module

var http = require('http');

//Lets define a port we want to listen to

const PORT=8080;

//We need a function which handles requests and send response

function handleRequest(request, response){

    response.end('It Works!! Path Hit: ' + request.url);

}

//Create a server

var server = http.createServer(handleRequest);

//Lets start our server

server.listen(PORT, function(){

    //Callback triggered when server is successfully listening. Hurray!

    console.log("Server listening on: http://localhost:%s", PORT);

});

Now to see Node’s magic simply start the server by running the file. In the terminal you can follow the below command to run your program:

> node myFirstHTTPServer.js

#output

Server listening on: http://localhost:8080

open up the url http://localhost:8080 on your browser and it should serve you the text returned from our program. Play with the path of the URL and see the message displayed.

Analysis of The Above Program

Now lets break the above program into sub blocks and see what's happening:

Loading the http Module

Node.js has core modules to create http/https servers, hence we have to import the http module in order to create an HTTP Server.

//Lets require/import the HTTP module

var http = require('http');

Defining the Handler Function

We need a function which will handle all requests and reply accordingly. This is the point of entry for server application, we can reply to requests as per our business logic.

//We need a function which handles requests and send response

function handleRequest(request, response){

    response.end('It Works!! Path Hit: ' + request.url);

}

Creating and Starting the Server

Here we are creating a new HTTP Server Object and then asking it to listen on a port. The createServer method is used to create a new server instance and it takes our handler function as the argument. Then we call listen on the server object in order to start it.

//Create a server

var server = http.createServer(handleRequest);

//Lets start our server

server.listen(PORT, function(){

    //Callback triggered when server is successfully listening. Hurray!

    console.log("Server listening on: http://localhost:%s", PORT);

});

Adding in a Dispatcher

Now that we have a basic HTTP Server running, it's time we implement some real functionality. Your server should respond differently to different URL paths. This means we need a dispatcher. Dispatcher is kind of router which helps in calling the desired request handler code for each particular URL path. Now lets add a dispatcher to our program. First we will install a dispatcher module, in our case httpdispatcher. There are many modules available but lets install a basic one for demo purposes:

> npm install httpdispatcher

If you’re unaware, npm is a package manager which provides a central repository for custom open sourced modules for Node.js and JavaScript. npm makes it simple to manage modules, their versions and distribution. We used the `npm install` command to install the required module in our project.

Now we will require the dispatcher in our program, add the following line on the top:

var dispatcher = require('httpdispatcher');

Now let’s use our dispatcher in our handleRequest function:

//Lets use our dispatcher

function handleRequest(request, response){

    try {

        //log the request on console

        console.log(request.url);

        //Disptach

        dispatcher.dispatch(request, response);

    } catch(err) {

        console.log(err);

    }

}

Let’s define some routes. Routes define what should happen when a specific URL is requested through the browser (such as /about or /contact).

//For all your static (js/css/images/etc.) set the directory name (relative path).

dispatcher.setStatic('resources');

//A sample GET request   

dispatcher.onGet("/page1", function(req, res) {

    res.writeHead(200, {'Content-Type': 'text/plain'});

    res.end('Page One');

});   

//A sample POST request

dispatcher.onPost("/post1", function(req, res) {

    res.writeHead(200, {'Content-Type': 'text/plain'});

    res.end('Got Post Data');

});

Now lets run the above program and try the following URL paths:

we can use our browser to do a GET request just by entering the URL in the address bar.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote