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');
我想知道为什么fs.stat回调中的write方法实际上并没有向客户端写任何内容。我相信res在范围内。
答案 0 :(得分:6)
您在res.end
之前致电res.write
。因此,什么都没有写出来。将调用移至res.end
进入stat处理程序:
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');
另请注意,您的原始代码易受directory traversal attacks 攻击,并且os.stat
和os.readFileSync
之间的race condition会受到影响。