You shall write a very basic web server in JavaScript that will run via nodejs Y
ID: 3820662 • 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_]*.html
URLs ending in .html, you will "serve" the file to the user's browser. These files should reside in a directory called "MYHTML". The "MYHTML" directory will be a subdirectory to the current director that your server runs. Your program shall return an error message if the file cannot be read or does not exist.
Explanation / Answer
Use the following code:
var http = require("http");
var paul = require('/homes/paul/HTML/CS316/p3_req.js');
var fs = require('fs');
var url = require('url');
// Now you create a server
http.createServer( function (request, response) {
// Parse the request containing file name
var pathname = url.parse(request.url).pathname;
// Print the name of the file for which request is made.
console.log("Request for " + pathname + " received.");
// Read the requested file content from file system
fs.readFile(homes/paul/HTML/CS316/p3_req.js, function (err, data) {
if (err) {
console.log(err);
// HTTP Status: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}
else{
//Page found
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.