Here are some functions I came up with to convert between url-encoding and Buffers (for any byte value including non-standard utf8):
const isUrlSafe = (char) => {
return /[a-zA-Z0-9\-_~.]+/.test(char)
}
const urlEncodeBytes = (buf) => {
let encoded = ''
for (let i = 0; i < buf.length; i++) {
const charBuf = Buffer.from('00', 'hex')
charBuf.writeUInt8(buf[i])
const char = charBuf.toString()
// if the character is safe, then just print it, otherwise encode
if (isUrlSafe(char)) {
encoded += char
} else {
encoded += `%${charBuf.toString('hex').toUpperCase()}`
}
}
return encoded
}
const urlDecodeBytes = (encoded) => {
let decoded = Buffer.from('')
for (let i = 0; i < encoded.length; i++) {
if (encoded[i] === '%') {
const charBuf = Buffer.from(`${encoded[i + 1]}${encoded[i + 2]}`, 'hex')
decoded = Buffer.concat([decoded, charBuf])
i += 2
} else {
const charBuf = Buffer.from(encoded[i])
decoded = Buffer.concat([decoded, charBuf])
}
}
return decoded
}
Examples:
> const buf = Buffer.from('4142432b', 'hex')
> const encoded = urlEncodeBytes(buf)
'ABC%2B'
> const encoded = 'ABC%2B'
> const buf = urlDecodeBytes(encoded)
<Buffer 41 42 43 2b>
encodeURIComponent()
is defined for strings. Why do you need it forBuffer
s? Can't you just use the original 'deadbeef' string?0xdeadbeef
would be ��'. Also see edit.