-
-
Save kaworu/2b5f20c6721d72b4e575dec7855ff0f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = require("util"); | |
function url_decode(urlencoded, callback) { | |
/* | |
* see https://tools.ietf.org/html/rfc3986#section-2.3 | |
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" | |
*/ | |
var unreserved = /[A-Za-z0-9\-\._~]/; | |
/* | |
* see https://tools.ietf.org/html/rfc3986#section-2.1 | |
* pct-encoded = "%" HEXDIG HEXDIG | |
*/ | |
var pct_encoded = /%[A-Fa-f0-9][A-Fa-f0-9]/; | |
var correctly_encoded = new RegExp( | |
"^(?:" + unreserved.source + "|" + pct_encoded.source + ")*$" | |
); | |
var splitter = new RegExp( | |
"(" + pct_encoded.source + ")" | |
); | |
if (!urlencoded.match(correctly_encoded)) | |
return callback(new Error("malformed data")); | |
var buffers = urlencoded.split(splitter).map(function (part) { | |
if (part.match(pct_encoded)) { | |
return Buffer.from(/* remove leading `%' */part.slice(1), "hex"); | |
} else { | |
return Buffer.from(part, "ascii"); | |
} | |
}); | |
return callback(null, Buffer.concat(buffers)); | |
} | |
var data = "salut%belol%f1foo%bebar"; | |
url_decode(data, function (err, buffer) { | |
if (err) | |
throw err; | |
console.error(buffer.toString()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment