是不是范围?(的node.js)

sig*_*lup 1 node.js

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');
Run Code Online (Sandbox Code Playgroud)

我想知道为什么fs.stat回调中的write方法实际上并没有向客户端写任何内容.我相信res在范围内.

phi*_*hag 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');
Run Code Online (Sandbox Code Playgroud)

另请注意,您的原始代码容易受到目录遍历攻击,并且在和之间存在竞争条件.os.statos.readFileSync

  • 我用更多的注释更新了答案 - **您当前的代码包含一个安全漏洞**. (2认同)