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 were 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

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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:

  • GET /page1 => 'Page One'
  • POST /page2 => 'Page Two'
  • GET /page3 => 404
  • GET /resources/images-that-exists.png => Image resource
  • GET /resources/images-that-does-not-exists.png => 404

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

Add a comment
Know the answer?
Add Answer to:
You shall write a very basic web server in Javascript that will run via nodejs. Your...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Project Description In this project, you will be developing a multithreaded Web server and a simple...

    Project Description In this project, you will be developing a multithreaded Web server and a simple web client. The Web server and Web client communicate using a text-based protocol called HTTP (Hypertext Transfer Protocol). Requirements for the Web server The server is able to handle multiple requests concurrently. This means the implementation is multithreaded. In the main thread, the server listens to a specified port, e.g., 8080. Upon receiving an HTTP request, the server sets up a TCP connection to...

  • This is in C. For this assignment we will write a simple database server. We will...

    This is in C. For this assignment we will write a simple database server. We will be creating a simple database of student records, so let’s describe these first. The format of a student record is as follows: typedef struct student {     char lname[ 10 ], initial, fname[ 10 ];     unsigned long SID;     float GPA; } SREC; Part One – the Server We will create a database server. The job of the server is to accept a...

  • You are to write a basic fitness application, in C++, that allows the user of the...

    You are to write a basic fitness application, in C++, that allows the user of the application to manually edit “diet” and “exercise” plans. For this application you will need to create three classes: DietPlan, ExercisePlan, and FitnessAppWrapper. Diet Plan Attributes: The class DietPlan is used to represent a daily diet plan. Your class must include three data members to represent your goal calories (an integer), plan name (a std::string), and date for which the plan is intended (a std::string)....

  • please use python and provide run result, thank you! click on pic to make it bigger...

    please use python and provide run result, thank you! click on pic to make it bigger For this assignment you will have to investigate the use of the Python random library's random generator function, random.randrange(stop), randrange produces a random integer in the range of 0 to stop-1. You will need to import random at the top of your program. You can find this in the text or using the online resources given in the lectures A Slot Machine Simulation Understand...

  • Program 7 File Processing and Arrays (100 points) Overview: For this assignment, write a program that...

    Program 7 File Processing and Arrays (100 points) Overview: For this assignment, write a program that will process monthly sales data for a small company. The data will be used to calculate total sales for each month in a year. The monthly sales totals will be needed for later processing, so it will be stored in an array. Basic Logic for main() Note: all of the functions mentioned in this logic are described below. Declare an array of 12 float/doubles...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT