I have a specific website where i would like to see how many views a certain page gets, with a text file being edited every time a person clicks on the page.
I've tried doing this myself but it did not work out,
I am not sure if i have done anything wrong here myself since i am still new to javascript.
var viewC = FileReader.readAsText('./views.txt');
var views = viewC + 1
var viewFile = " " + views +" ";
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(viewFile, 'views.txt', 'text/plain');
For a more detailed description of what i would like to happen : "When the user goes to the page, the code will run and add a new value to the text file. The new value is +1 of the old value that is there."
Expected result -
TXT file before
TXT file after a person views it 1
TXT file after the second view 1 2
Or if it is possible to remove the old number and add the new number
Related
I am using a nodeJS program as a server and an AngularJS web application as the client.
To create the CSV I'm using the "express-csv" library (https://www.npmjs.com/package/express-csv)
Here is my server side code:
Defines:
var app = express();
var csv = require('express-csv');
Get code:
app.get('/exportDB', function(req, res){
res.csv([
["a", "b", "c"]
, ["d", "e", "f"]
]);
Here is my client side code:
$http.get("http://"+$localStorage.ip+":"+$localStorage.port+"/exportDB").success(function(response){
// HERE I NEED A WAY TO DOWNLOAD THE RECEIVED CSV
});
Needless to say it reaches the server and everything else is working just fine, but I couldnt find a way to download the CSV. Help please.
P.S
Please don't say it's a duplicate of Prompt a csv file to download as pop up using node.js and node-csv-parser (node module) since the client side isn't really mentioned there.
Also, other questions are focused on server side instead of client.
There is no other question referring to AngularJS client.
You can just navigate:
location.href = "http://"+$localStorage.ip+":"+$localStorage.port+"/exportDB";
I faced same issue that the solutions mentioned above with works well with Chrome and Firefox, but not with safari/IE.
Tried out following hack and it worked for me-
var url="http://'+$localStorage.ip+':"+$localStorage.port+'/exportDB';
var form = angular.element("<form action='" + url +"'></form>");
form.submit();
File download will be handled by browser itself.
though following is limitation to it -
You won't be able to handle the errors (if any) from your http get call :( For this tried using try-catch block of javascript, but didn't work well...
..you wont be able to unit test this piece of code :( :(
There is another approach that worked and it was -
var url="http://'+$localStorage.ip+':"+$localStorage.port+'/exportDB';
$window.location.href = url;
Suggestions and Discussions welcome!
You can create a tag and click on it:
$http.get("http://"+$localStorage.ip+":"+$localStorage.port+"/exportDB").success(function(response) {
var dataURI = 'data:application/octet-stream;base64,' + btoa(response);
$('<a></a>').attr({
download: 'db.csv',
href: dataURI
})[0].click();
});
There are ways of downloading csv. First approach is to create a tag and click it
Add the mimeType in below code data:application/octet-stream
var a = document.createElement('a');
a.href = 'data:'+mimeType+';charset=utf-8;base64,' + response;
a.target = '_blank';
a.download = "name the file here";
document.body.appendChild(a);
a.click();
But this solution doesn't work on IE>9 and safari>6
because safari doesn't follow download attribute for anchor tag
so for safari you can use filesaver.js
and IE this solution will work
if (window.navigator.msSaveOrOpenBlob){
// base64 string
var base64str = response;
// decode base64 string, remove space for IE compatibility
var newstr =base64str.replace(/\s/g, '');
var binary = atob(newstr);
// get binary length
var len = binary.length;
// create ArrayBuffer with binary length
var buffer = new ArrayBuffer(len);
// create 8-bit Array
var view = new Uint8Array(buffer);
// save unicode of binary data into 8-bit Array
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
// create the blob object with content-type "application/csv"
var blob = new Blob( [view], { type: mimeType });
window.navigator.msSaveOrOpenBlob(blob, "Name your file here");
}
Here I tried to make it simple. Assign all the back end records that you want to display in the file in the variable called obj. I will just say it as var obj = []. And inside the function just add the below code.
var a = document.createElement("a");
var csvContent = "Name, Address\n";
for(var i =0; i <obj.lenght; i++ ) {
var dataString = obj[i].name + ", " + obj[i].address + "\n";
csvContent += dataString;
}
a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(csvContent);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
Please find the following code for more information.
function dataToCSVTry(arr) {
var fileName = "CSVFile";
var data = "";
for (var i = 0; i < arr.length; i++) {
data += (arr[i].id + " , " + arr[i].time + "\r\n");
}
var url = 'data:text/csv;charset=utf8,' + encodeURI(data);
window.open(url, '_blank');
window.download = (url + ".txt");
var encodedUri = encodeURI(url);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
link.click();
};
`
This is a function to which I'm providing JSON data as input and after that trying to convert it in to a CSV(Comma Separated Values) using a for loop.
After that i am trying to save it in both .txt and .csv format. As .txt is getting saved easily, the problem comes in excel file where the data comes like :
"1%20%2C%20161.963%0A%0D%0A2%20%2C%20473.222%0A%0D%0A3%20%2C%20error%0A%0D%0A"
where some code (from what I think) is for blank space("%20%2C%20") and some other code("%0A%0D%0A") is for newline characters. What needs to be done in order to create Excel file in the same CSV format? Is there any problem with the encodeURI part that I am using ?
Data url content isn't URI encoded, it is base-64 encoded. You should use btoa or a similar solution to create your data from the CSV string you built.
I'm trying to fill some inputs when you load a page, using the data I have from a .txt file. This file has a list of numbers
1
2
3
Something like this. So I wanted to read this lines and put them in their corresponding input. Suggestions on how to do this??
I tried with this code, but maybe I have a mistake that I don't know about, I'm starting with javascript.
function loadvalues()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("E://Steelplanner/Demand_Routing/Pruebas/OrderBalancing_Masivos/ModificaFechaTope/DueDate/Datosactuales.txt", true);
var Ia5 = document.getElementById("Ia5sem");
var text = s.ReadLine();
Ia5.value = text;
Try using file.ReadLine() until document not completely read using while loop with AtEndOfStream of file variable.
Here is example you can refer: ReadLine Method
Don't forget to replace TextFile path to your own text file path
My text file contains same data as in your example
<script type="text/javascript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
//specify the local path to Open and always add escape character else throw error for bad file name
var file = fso.OpenTextFile("C:\\Users\\MY_USER\\Desktop\\txtfile.txt", 1);
var Ia5 = document.getElementById("Ia5sem");
while (!file.AtEndOfStream) {
var r = file.ReadLine();
Ia5.innerHTML = Ia5.innerHTML + ("<br />" + r);
}
file.Close();
</script>
<p id="Ia5sem">HI</p>
So, I don't know why, but I just changed the name of the variables and made a slight change in the .OpenTextFile line and it worked.
function loadvalues()
{
var file = new ActiveXObject("Scripting.FileSystemObject");
var text = file.OpenTextFile("E:\\Steelplanner\\Demand_Routing\\Pruebas\\OrderBalancing_Masivos\\ModificaFechaTope\\DueDate\\Datosactuales.txt", 1,false);
var Ia5s = document.getElementById("Ia5sem");
Ia5s.value = text.ReadLine();
var Ia4s = document.getElementById("Ia4sem");
Ia4s.value = text.ReadLine();
text.close();
}
Anyways, I'm gonna check the FileReader() for future references and the script #Sarjan gave, maybe I can improve it, but I have other things to finish. Thanks for everything.
I have a JavaScript method that asynchronously accepts a blob of an ms-word document. How can I open this as a word doc? I've tried:
function openDocAsync(blob) {
var wblob = new Blob([blob], { type: "application/msword" });
var status = navigator.msSaveOrOpenBlob(wblob);
}
I've also tried using:
var bb = new MSBlobBuilder();
bb.append(blob);
var nblob = bb.getBlob();
Neither to any avail. With the first option, msSaveOrOpenBlob, I can get Word to open a file of gibberish (base 64 encode of the binary), but not the desired contents.
How can I create a new Word doc using the blob supplied?
Thanks in advance
I have this code to export a filtered html table. I have two issues with it which I can't figure out:
1) I get "•" instead of a bullet point • in my exported .csv file. I've tried changing charset from UTF-8 to iso-8859 in meta head and this script but this didn't help.
2) When I have quotes in the sentence it treats it as a comma and breaks the sentence, putting it into a next cell. Example:
I am a "good" man with a good reputation would be broken into something like:
A1 I am a "good" man with
B1 good reputation
I can't work it out why this happens?Thanks!
<script type='text/javascript'>//<![CDATA[
$(function(){
$('#downloadButton').click(function () {
var keepOnlyA1= true // put this true to remove unused numeric A0 field from each row [ A0, A1=[field,field,...]]
//
var a= tf_table1.GetFilteredData(true) // a= [ [A0,A1=[field,field,...]], [A0,A1=[field,field,...]], ...[..,[...]] ]
// ^a[0] ^a[1] ^a[n]
for (var i=0,row,r1; i<a.length; i++){ //
row= a[i] // row= [A0, A1=[field,field,...]]
r1= row[1] // ^r1
for (var j=0; j<r1.length; j++){ // surround each field with quotes "field"
r1[j]= '"'+r1[j].replace('"','""')+'"' // if there is any " already inside field string, it needs to be doubled. per csv rfc.
} //
if (keepOnlyA1) a[i]= r1 // if true, just replace each row array with its single interior A1=[field,field,...] array
} //
var colvals = a.join("\r\n") +"\r\n" //
var blob = new Blob([ colvals ], {type: 'text/csv;charset=ISO-8859;'});
//var filename = $('#fileName').val();
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, "S7_Won_Tendes_Export_Filtered.csv");
}
else {
var a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.style.display= "none" //added// invisible
document.body.appendChild(a) //added// firefox wouldn't click() it without being appended
a.click();
//if (a.remove) a.remove();
a.parentNode.removeChild(a) //added//
}
});
});//]]>
</script>
Ok I managed to find answers:
Replace
var blob = new Blob([ colvals ],
with
var blob = new Blob(["\uFEFF" + buffer],
and
r1[j]= '"'+r1[j].replace('"','""')+'"'
with
r1[j]= '"'+r1[j].replace(/"/g, '""')+'"'