I created a BasicWebServer.js
file which lives in the folder portfolio-website
and this folder has the following files: index.htm
, BasicWebServer.js
, css/style.css
.
The code I put in the BasicWebServer.js file is as following:
var http = require('http'),
fs = require('fs'),
path = require('path'),
host = '127.0.0.1',
port = '9000';
var mimes = {
".htm" : "text/html",
".css" : "text/css",
".js" : "text/javascript",
".gif" : "image/gif",
".jpg" : "image/jpeg",
".png" : "image/png"
}
var server = http.createServer(function(req, res){
var filepath = (req.url === '/') ? ('./index.htm') : ('.' + req.url);
var contentType = mimes[path.extname(filepath)];
// Check to see if the file exists
fs.exists(filepath, function(file_exists){
if(file_exists){
// Read and Serve
fs.readFile(filepath, function(error, content){
if(error){
res.writeHead(500);
res.end();
} else{
res.writeHead(200, { 'Content-Type' : contentType});
res.end(content, 'utf-8');
}
})
} else {
res.writeHead(404);
res.end("Sorry we could not find the file you requested!");
}
})
res.writeHead(200, {'content-type' : 'text/html'});
res.end('<h1>Hello World!</h1>');
}).listen(port, host, function(){
console.log('Server Running on http://' + host + ':' + port);
});
UPDATE 1 Part 1)
I removed the two lines:
res.writeHead(200, {'content-type' : 'text/html'});
res.end('<h1>Hello World!</h1>');
and when I refresh the page, I get:
Sorry we could not find the file you requested!
Part 2) I have also tried piping it by doing this:
var http = require('http'),
fs = require('fs'),
path = require('path'),
host = '127.0.0.1',
port = '9000';
var mimes = {
".htm" : "text/html",
".css" : "text/css",
".js" : "text/javascript",
".gif" : "image/gif",
".jpg" : "image/jpeg",
".png" : "image/png"
}
var server = http.createServer(function (req, res) {
var filepath = (req.url === '/') ? ('./index.htm') : ('.' + req.url);
var contentType = mimes[path.extname(filepath)];
// Check to see if the file exists
fs.exists(filepath, function(file_exists){
// if(file_exists){
// // Read and Serve
// fs.readFile(filepath, function(error, content){
// if(error){
// res.writeHead(500);
// res.end();
// } else{
// res.writeHead(200, { 'Content-Type' : contentType});
// res.end(content, 'utf-8');
// }
// })
res.writeHead(200, {'Content-Type' : contentType});
var streamFile = fs.createReadStream(filepath).pipe(res);
streamFile.on('error', function() {
res.writeHead(500);
res.end();
})
} else {
res.writeHead(404);
res.end("Sorry we could not find the file you requested!");
}
})
}).listen(port, host, function(){
console.log('Server Running on http://' + host + ':' + port);
});
This gives the following error:
SyntaxError: Unexpected token else
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3