Not terribly interesting superhero
Blobs are not terribly interesting by themselves
Behind this unflattering quote is an almost unknown JavaScript object that saved my day. We needed to fake a CSV file generated on the client side. The known and documented solution is:
button.on("click", function(){ var csv = ''; for(var i = 0; i< 50000; i++){ // let's fake something csv += Math.random() + '\n'; } var link = document.createElement("a"); link.setAttribute("href", 'data:text/csv;charset=utf-8,' + csv); link.setAttribute("download", 'numbers.csv'); document.body.appendChild(link); link.click(); })
But apparently, this solution will fail on elements larger than 1.3M, depends on the client circumstance. To see how it fails, just increase the loop.
Then I found the Blob: “A Blob is an opaque reference to, or handle for, a chunk of data. The name comes from SQL databases, where it means “Binary Large Object.” In JavaScript… neither is required”. Such a mistreated object that even the formal guides mock him.
Blob
A blob is a file-like object that can store a big about of data. That’s why it sometimes stored in memory, and sometimes on the disk. Sometimes treated asynchronously and sometimes not. Did I mention mistreatment?
button.on("click", function(){ var csv = ''; for(var i = 0; i< 5000000; i++){ csv += Math.random() + '\n'; } var blob = new Blob([csv], {type: 'text/csv'}); var link = document.createElement("a"); link.href = window.URL.createObjectURL(blob); link.download = 'numbers.csv'; document.body.appendChild(link); link.click(); })
As you can see, we create the blob with two arguments: the content and additional settings. In addition to text, we can pass any binary data, like images, videos or Sigur Ros lyrics.
let a = new Blob(value,{type: 'application/octet-stream'}); a.type == "application/octet-stream"; let b = new Blob(value,{type: 'text/css'}); b.type == "text/css"; let svefnGEnglar = "(Ég) er kominn aftur (á ný) Inn í þig (Það er) svo gott að vera (hér) En stoppa stutt við"; let c = new Blob([svefnGEnglar],{type: 'Sigur/Ros'}); c.type == "sigur/ros";
As mentioned Blob is a file-like object, and can be used with file readers:
var blob = new Blob(["bla bla"], {type : "text/plain"});
var fileReader = new FileReader();
fileReader.addEventListener("loadend", function(e){
console.log(e);
});
myReader.readAsText(blob);
Or to read HTTP request just by setting the response type to blob:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://whatsoever.bla");
xhr.responseType = "blob";
xhr.onload = function()
{
console.log(xhr.response);
}
xhr.send();
Are the blobs still “not terribly interesting by themselves”? I know some people that will claim the same definition applies to the developers themselves, but we all now that only true for BE developers 😉