var http = require('http');
var url= require('url');
var util= require('util');
var fs = require('fs');
var body_404="<html><body><center>404 error</center></body></html>";
http.createServer(function (req,res) {
var what = url.parse("http://127.0.0.1:1235"+req.url);
var pathname = what.pathname;
switch(pathname) {
case "/":
pathname="/www/index.html";
default:
res.writeHead(200, {'Content-type' : 'text/html'});
ret = res;
fs.stat("."+pathname, function (err, stat) {
if(err)
res.write(body_404);
else
res.write(fs.readFileSync("."+pathname));
});
res.end();
break;
}
}).listen(1235, '127.0.0.1');
I am wondering why the write method inside the fs.stat callback does not actually write anything, it seems, to the client. I believe res is in scope.
You're calling res.end
before res.write
. Therefore, nothing gets written out. Move the call to res.end
into the stat handler:
var http = require('http');
var url= require('url');
var util= require('util');
var fs = require('fs');
var path = require('path');
var body_404="<html><body><center>404 error</center></body></html>";
var rootPath = path.abspath(".");
http.createServer(function (req,res) {
var what = url.parse("http://127.0.0.1:1235"+req.url);
var pathname = what.pathname;
var buffer;
switch(pathname) {
case "/":
pathname="/www/index.html";
default:
var filename = path.join(rootPath, pathname);
if (filename.indexOf(rootPath) !== 0) {
res.writeHead(400, {'Content-type': 'text/plain'});
res.write('Directory traversal attack averted.');
res.end();
return;
}
fs.readFile(function (err, content) {
if(err) {
res.writeHead(404, {'Content-type' : 'text/html'});
res.write(body_404);
} else {
res.writeHead(200, {'Content-type' : 'text/html'});
res.write(content);
}
res.end();
});
break;
}
}).listen(1235, '127.0.0.1');
Also note that your original code is vulnerable to directory traversal attacks, and suffers from a race condition between os.stat
and os.readFileSync
.