Created
July 11, 2019 17:29
-
-
Save Dletta/0574357fe44611239b83c43eb9d604ba to your computer and use it in GitHub Desktop.
sending JSON objects via Blobs
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 obj = {name:"test", result:"hello world"}; | |
var string = JSON.stringify(obj); | |
console.log(obj) | |
var arr = []; | |
encode = Array.from(string); | |
while(encode.length>0){ | |
arr.push(encode.shift().charCodeAt(0)); | |
} | |
var u16 = new Uint16Array(arr); | |
var blob = new Blob([u16], {type:'application/json'}); | |
console.dir(blob); | |
//send blob via socket | |
// received and read back | |
var reader = new FileReader(); | |
reader.onload = function(e) { | |
// The file's text will be printed here | |
console.log(e.target.result) | |
var res = new Uint16Array(e.target.result); | |
console.log(String.fromCharCode(res[0]),String.fromCharCode(res[1]),String.fromCharCode(res[2])) | |
var result = Array.from(res); | |
var output = ""; | |
while(result.length>0){ | |
output += String.fromCharCode(result.shift()) | |
} | |
console.log(JSON.parse(output)); | |
}; | |
reader.readAsArrayBuffer(blob); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment