var http = require('http'),
fs=require('fs'),
path=require('path'),
host ='127.0.0.1',
port='9001';
var mimes = {
".htm":"text/html",
".css":"text/css",
".js":"text/javascript",
".gif":"text/gif",
".jpg":"text/jpeg",
".png":"text/png"
}
var server = http.createServer(function(req,res){
var filepath =(req.url==='/')?('./index.htm'):('.'+req.url);
var contentType = mimes[path.extname(filepath)];
//check file exists or not
fs.exists(filepath,function(file_exists){
if(file_exists)
{
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);
})
In the above code my node server is giving message its runs in 127.0.0.1:9001, but when I run it in my browser I face "error 404 file not found", which is not the error I mentioned. Also I have index.html file inside the same folder of this script file. What's wrong with my code?
You code works fine for me.
You should have index.htm
file in the same folder you execute the server.js
file.
Change the if condition
index.html != index.htm