I'm in a bit of a predicament. I'm new to coding in general, and this is my assigned program for my JavaScript class this week. We are supposed to create a web server that serves files from a file system, that also implements Node modules. It must be able to read HTML, css, gif, and js resources. These files will be placed within the same folder as the script, under a /scripts and /html directory. Here is the logic I have tried to implement, however my terminal keeps telling me path.extname(resource) is an undefined function. It's quite ugly, I know, but I'm still trying to wrap my head around this concept. Any help would be great, I have been trying to figure this out for the past day.
'use strict';
// Load the file system module
var fs = require('fs');
// load the http module
var http = require('http');
// load the url module
var url = require('url');
// load the path module
var pathModule = require('path');
// The following function will be called when the server
// is handling a request
function servePage(request, response) {
// get path name and remove '/'
var path = url.parse(request.url).pathname.substring(1);
// if path is an empty string
if (path === '') {
path = './html/home.html';
}
// Read the file asynchronously; HTML
fs.readFile(path, function (err, content) {
var extension = path.extname(path);
switch (extension){
case '.hmtl':
response.writeHead(200,
{'Content-Type': 'image/gif'});
response.write(content); // Send file contents as response body
response.end();
break;
case '.gif':
response.writeHead(200,
{'Content-Type': 'text/html; charset = UTF-8'});
response.write(content); // Send file contents as response body
response.end();
break;
case '.css':
response.writeHead(200,
{'Content-Type': 'text/css; charset = UTF-8'});
response.write(content); // Send file contents as response body
response.end();
break;
case '.js':
response.writeHead(200,
{'Content-Type': 'application/javascript; charset = UTF-8'});
response.write(content); // Send file contents as response body
response.end();
break;
case 'err':
response.writeHead(404,
{'Content-Type': 'text/plain; charset = UTF-8'});
response.write(err.message +
' - The page requested was not found.');
response.end(); // Done
break;
}
/* }
if (err) { // If there is an error, set the status code
response.writeHead(404,
{'Content-Type': 'text/plain; charset = UTF-8'});
response.write(err.message +
' - The page requested was not found.');
response.end(); // Done
// else if the content was succesfully read
} else {
response.writeHead(200,
{'Content-Type': 'text/html; charset = UTF-8'});
response.write(content); // Send file contents as response body
response.end();
} */
});
}
// create a server object
var server = http.createServer(servePage);
server.listen(8080);
console.log('Server running at http://localhost:8080');
require'd thepathmodule into thepathModulevariable. UsepathModule.extname(resource).