Download Blob as file in Javascript

While we are working with Javascript we may find our self in a situation where we need to let users download blob as File.

So In this post, I’ll share basic javascript function which allows us to download blob as a file in the browser.


const downloadBlobAsFile = function(data, filename){
				const contentType = 'application/octet-stream';
        if(!data) {
            console.error(' No data')
            return;
        }

        if(!filename) filename = 'filetodonwload.txt'

        if(typeof data === "object"){
            data = JSON.stringify(data, undefined, 4)
        }

        var blob = new Blob([data], {type: contentType}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a')

        a.download = filename
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl =  [contentType, a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
    }
    
    // call the function 
    const data = "some data";
    const fileName = "filetodonwload.txt";
    downloadBlobAsFile(data, fileName);

You can find a working sample here. 

🙂

Difference between == and === in JavaScript

So we know in javascript we have == and === comparisons. Why two? What are the differences between them?

So what is the difference between followings


'1' == 1

this returns true.

when it comes === equals


'1' === 1

this returns false.

So what it is?

The triple-equals comparator compares both type and contents

So ‘1’ === 1 contains string value and int value. Even contents are same they are in different types. So it is not equals.

Double equals tries to help with type coercion. But it’s not always the help we want. So keep in mind when you are using above equal comparisons.
 

json date to javascript date

json date string comes like below.

“/Date(1238540400000)/”

While I was developing I wanted convert into javascript date and get date in “mm/dd/yyyy” format.

The I am using below function to get it done.


function parseJsonDate(jsonDateString) {

var date; var newDate;
if (jsonDateString) {
date = new Date(parseInt(jsonDateString.replace('/Date(', '')));
newDate = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();

 return newDate;
 }
}

I think this might help you….