2012-04-12 149 views
0

我想在node.js中從/very///bad/%D0%B9/../../../../../request/../ok/%C3%A4.txt獲得/ok/ä.txt。我發現了以下方法:從nodejs構建路徑request.url路徑名

var url = require('url'), path = require('path'); 
require('http').createServer(function (request, response) { 

    var file = null; 
    try { 
     file = path.normalize(decodeURI(url.parse(request.url).pathname)); 
    } catch (e) { 
    } 

    console.log(file); 
    response.end(); 
}).listen(3002, '127.0.0.1'); 

有沒有更好的方法存在,沒有try/catch塊?

回答

0

我想你可以擺脫try..catch塊,因爲path.normalizedecodeURI不會拋出一個錯誤,url.parse只拋出一個錯誤,如果該參數是string型不:

... 
if (typeof url !== 'string') { 
    throw new TypeError("Parameter 'url' must be a string, not " + typeof url); 
} 
... 

而且由於request.url是總是類型string這也不會發生。