I am passing text files back and forth between Python and JavaScript.
Although urllib.parse.quote (Python side) and decodeURIComponent (JavaScript side) seems to work OK, it may not work for every character correctly.
So I wrote my own function that should be 100% reliable, regardless of the characters in the text file.
On the Python side I use xxd to encode the file. xxd is a linux utility that converts the binary file to a string of 2 hex digits for each binary byte. The Python code to encode the file to a string of of hex codes from Python is:
mystring = os.popen("xxd -p "+your_file_name_here).read().replace('\n','')
If you want to do the xxd conversion in Python instead of using the external program, you can use these functions. They only work with text files, though. If you need to work with binary, stick with the external xxd program.
def doxxd(s):
xd=""
c=""
for i in range(0,len(s)):
if (ord(s[i]))<16:
c=hex( ord(s[i]) ).replace('0x','0')
else:
c=hex( ord(s[i]) ).replace('0x','')
xd+=c
return xd
def unxxd(x):
s=""
#get two chars at a time
for i in range(0,len(x),2):
s+=chr(int('0x'+x[i:i+2],16))
return s
On the JavaScript side this function restores the hex code file back to the original text string:
function unxxd(str){
var s=""
//get two chars at a time
for (i=0;i<str.length;i=i+2){
s+=String.fromCharCode(parseInt("0x"+str.substr(i,2)))
}
return s
}