How to create auto loading index like apache

11 views
Skip to first unread message

Георги Няголов

unread,
Jun 3, 2017, 2:47:31 PM6/3/17
to nodejs
Hello, I'm trying to do web server which automatically opens index.html but failed
this is my code
var http = require('http');
var url = require('url');
var fs = require('fs');
const por = 8080;

//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 request file content from file system
 fs
.readFile(pathname.substr(1), function (err, data) {
 
if (err) {
 
//HTTP status: 404

 
//print error
 console
.log(err);
 response
.writeHead(404, {'Content-type': 'text/html'});

 
} else {
 
//Page found, HTTP Status: 200 : OK

 response
.writeHead(200, {'Content-type': 'text/html'});
 
switch (request.method){
 
case "GET":
 
if (request.url !== "/") {
 console
.log("Another");
 response
.write(data.toString());
 
} else {
 console
.log("Index");
 
}
 
break;
 
default:
 
break;
 
}

 
}response.end();
});

}).listen(por);
console
.log("Server runing on http://1270.0.1:8080");

When type localhost:8080 throw me error

Request for / received.
{ Error: ENOENT: no such file or directory, open ''
 at
Error (native) errno: -2, code: 'ENOENT', syscall: 'open', path: '' }

I know if type localhost:8080/index.html will work, but that's not the effect I'm looking for.
Reply all
Reply to author
Forward
0 new messages