I want to get /ok/ä.txt
from /very///bad/%D0%B9/../../../../../request/../ok/%C3%A4.txt
in node.js. I discovered the following method:
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');
Does some better method exist, without the try/catch block?
I think you can just get rid of the try..catch
block, because path.normalize
and decodeURI
never throw an error and url.parse
only throws an error if the parameter is not of type string
:
...
if (typeof url !== 'string') {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
...
and since request.url
is always of type string
that won't happen either.