If I'm reading data "array" from javascript file, and I want to change an element value in the array, how can I apply this update on the javascript file "save the javascript file with new value".
var country = document.getElementById('edit_country').value;
for (i = 0; i < country_arr.length; i++) {
if(country_arr[i] == country) {
var city = "|".concat(document.getElementById("add_city").value);
city_arr[i] = city_arr[i].concat(city);
}
}
You cannot edit a file from a computer with Java Script, the best thing you can do is to create a new file with it and download it. To download a file containing a JSON check this other question: Link
Related
I am working on an Adobe Illustrator JavaScript and need to load data from a CSV file on my computer as an array into the script so I can work with them later (everything Is happening on my computer, and nothing happens online/web browser.) I need every line of the text in the CSV to be separated in the array, and then I need to separate the words in the line into an array so that I have an array of arrays in the end. Each line has three variables which get fed into a function that has to happen for each line.
The error I am getting from the code below says:
'Error 25: Expected: ;. -> let reader = new FileReader();'
var csv = Folder ("Path to my csv file");
function processData(csvFile) {
let reader = new FileReader();
reader.readAsText(csvFile);
reader.onload = function(event) {
var allText = reader.result;
};
const allTextLinesArr = allText.toString().split(/\r\n|\n/);
var alen = allTextLinesArr.length;
const allTextLinesArrArr = [];
for (var i=1; i<=alen; i++) {
allTextLinesArrArr[i-1] = allTextLinesArr[i-1].split(",");
}
for (var i=1; i<=alen; i++) {
doStuff(allTextLinesArrArr[i-1][0],allTextLinesArrArr[i-1][1],allTextLinesArrArr[i-1][2]);
}
}
Here is the classic native Extendscript way to read CSV data from a file:
var csv_file = File('test.csv');
csv_file.open('r');
csv_file.encoding = 'utf-8';
var data = csv_file.read().split('/\r\n|\n/'); // split by lines
csv_file.close();
for (var row in data) data[row].split(','); // split all lines by comas
alert(data); // here is your 2d array
Error 25 isn't a standard Javascript error that you'd ever see in a web browser.
Are you using something like Adobe ExtendScript perhaps? If so, perhaps update your question with exactly where this code is being used.
The answer however, is probably that the program that you're using has an old version of Javascript that doesn't support FileReader (which is a fairly new bit of Javascript code).
It's also worth noting that you wouldn't usually be able to access the user's file from Javascript (without the user selecting it manually). However, it's possible that the program you're using to run JS does support this.
So in a client-side HTML page, a user selects a file and uploads it to the JavaScript code. JavaScript parses the file and sends it to the server and back to everyone else who is on the site. Then every client makes a blob download link for the file. It's easy when I can send the file to server and back like this.
But now, I want to make that file available for future users of the site without saving it to a location. This is in a chat program, so I've been sending messages from users as strings to a database. I'd like to create a program to send the aforementioned File object to the shortest string possible and then recreate the file (including all metadata) at another client from this string.
What is the standard way to convert a Blob to a string and back again without losing anything? If there's multiple ways, what results in the shortest string?
I found the answer to my question, I had to modify some other answers from SO questions that only sorta applied to my question. Here's what I found:
This is on the uploading-client, in the function called when a file is uploaded:
let inp = document.getElementById("file_input");
let reader = new FileReader();
reader.onload = function(){
send_off_to_other_clients(reader.result);
}
reader.readAsBinaryString(inp.files[0]);
On the other clients:
<script>
function get_blob_from_string (string, type, name) {
let array = new Uint8Array(string.length);
for (let i = 0; i < string.length; i++){
array[i] = string.charCodeAt(i);
}
let end_file = new Blob([array], {type: type, name: name});
let a = document.createElement("a");
a.href = URL.createObjectURL(end_file);
a.download = name;
a.target = "_blank";
a.click();
}
</script>
end_file is the returned-to-blob version, and then I create an anchor tag to download it. Probably isn't "proper" but it works.
I have a slide interface in jQuery that loads a JSON file on each new slide. The JSON files are named with sequential numeric values (1.json, 2.json..) to determine the order of the slides. I would like this to be a value in the object ("index-position") rather than the name of the file.
My question is how would I load these files sequentially in the same manner - but rather than load the order by file name, load them by index position?
My hunch is that this means creating an array of 'index-position' values of all the files and associating each index to a file name, but perhaps there is a simpler/more efficient method?
Thanks
You can read the content of the json before (read the "index-position") and set it to your global array.
Something like:
var slides = [];
$.getJSON( "ajax/fileName.json", function( data ) {
var index = data["index-position"];
slides[index] = data;
}
No magic solution. You must get the files connected to an index in some format (for example ["1.json", "2.json"]). You can put this information in another external file and use it, or you can save an network request by making it hard coded in your code, like this:
var files = ["1.json", "2.json"];
var obj = {};
for (i = 0; i<10; i++)
{
obj[i] = i + ".json";
}
console.log(obj[0], obj[1]);
//0.json, 1.json
I have a code which converts JSON to CSV. And I put this through a specific condition ( if condition) I want the CSV to be downloaded automatically if the condition is met without any button click. what is the shortest/simplest way to do this?
For eg:
if( data.length == 10){
var stored_data = data;
data = [];
console.log(stored_data);
var csv_file = ConvertToCSV(stored_data); //ConvertTOCSV is a function
}
if the above condition is met, the CSV should be downloaded. Thank you
NOTE: I know this can e done easily with a button click. but i want the download to happen automatically when the condition is satisfied
Just create a "dummy" link and programmatically set its href and then click. The link shouldn't appear on the screen because it has no content.
<body>
<a href="#" id="csvDownload" download></a>
</body>
<script>
if( data.length == 10){
var lnk = document.getElementById("csvDownload");
var stored_data = data;
data = [];
console.log(stored_data);
var csv_file = ConvertToCSV(stored_data); //ConvertTOCSV is a function
lnk.href = csv_file;
lnk.click();
}
</script>
What you are trying to do is possible by changing the document location to point to your created object, but the problem that I ran into while trying to create a quick example for you, is I can't seem to give the file a usable name and extension. So everything downloaded as a file called "download" with no extension (however - the file contents are correct).
So if you want to pursue finding a way to give the stream a name and file type you could start with something like this -
document.location='data:Application/octet-stream,' +
encodeURIComponent(csv_file);
But I would say that #Scott's answer is a better way to go.
i have an array called items=["apple","mango","cherry"];
i wonder how i can load the array data from text file instead of declaring it?the text file data is stored like this "apple","mango","cherry",...
furthermore, how to add to the end of this this text file an item for example add "orange" after "cherry"?
items=["apple","mango","cherry"];
if (items.indexOf(myVariable2) == -1) {
// not found, so output it
t++;
document.myform3.outputtext3.value +=myVariable2+"\n";
}
With jQuery you can do something like this
$.get("textFile.txt", function(data) {
var items = data.split(',');
});
You may need something like this though
var items = data.replace(/"/g, '').split(',');
This is a start.
If this is a user input file then you may need to upload it before you work with it.
Sorry, but I don't believe it's quite that simple. Browsers restrict access to local drives (and to server drives) for security reasons.
But one way to access the text file using jQuery would be
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
var file = event.target.file;
var reader = new FileReader();
var txt=reader.readAsText(file);
var items=txt.split(",");