Bolboa Bolboa - 18 days ago 5
Javascript Question

Using javascript Blob to save data as a CSS file

I have the following function to save a file to the browser using

blob
...

var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());


I am passing the following data to it...

var filename = "style.css";
var data = CSSFile //CSS string

saveData(data, filename)


My
data
is a string of CSS attributes that I want to save as a CSS file. The problem is, when I open the downloaded CSS file, it look like...

"html, body {....} ... "


Notice it is surrounded by double quotes. I need these removed. I tried the following...

CSSFile = CSSFile.substring(0, CSSFile.length - 1);
saveData(data, filename)


But all that did was remove the first character inside the double quotes...

"tml,body{...}..."


How can I save the string without the double quotes?

Answer

You are getting quotes in your string because you are running it through JSON.stringify when it is already a string.

Try this instead.

var saveData = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, fileName) {
        var blob = new Blob([data], {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());