Reputation: 141
I have a data file, newline delimited, of a variety of names I want to pull into an array for processing in JavaScript. This set of names will eventually need to be sorted, but right now I'm working on the actual file loading process. Here is my code as it stands right now.
var nameslist = document.baseURI.split('.'); nameslist.pop(); nameslist = nameslist.join('.') + ".dat";
console.log("Attempting to read from file: " + nameslist);
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
reader.open("GET", nameslist, false);
reader.send(null);
nameslist = reader.responseText.split('\n');
nameslist.pop();
console.log("Elements read: " + nameslist.length);
As expected with the data file consisting of three names (for the test case) I get the following result in my console log...
"Attempting to read from file: file:///home/username/Desktop/test/test.dat" test.js:11
"Elements read: 3" test.js:19
The problem is I get the following warning and error in my log as well, which I would like to eliminate (as simply ignoring it could lead to issues later down the line)...
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/ test.js:14
syntax error test.dat:1
From my research into the warning about depreciation, it seems Javascript as a language dislikes synchronous operations, as it slows down the script's running speed. In this case however, I need to have everything loaded before the rest of the script can meaningfully run. I know I could refactor this to put the rest of the script in a function that is called after the data is pulled off responseText, and just use a true on the reader.open line, but is there a better way to get JavaScript to synchronously load the data file in question without having to start making a main() function that is only going to get called once?
As for the rogue error pointing to the first line of the data file, I'm frankly stumped. Any ideas on what could be causing this behaviour?
Thanks in advance for any answers I get from the community.
Upvotes: 0
Views: 1354
Reputation: 141
Solved by rewriting the code as follows:
var nameslist = document.baseURI.split('.'); nameslist.pop(); nameslist = nameslist.join('.') + ".dat";
console.log("Attempting to read from file: " + nameslist);
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
reader.open("GET", nameslist);
reader.onloadend = main;
reader.responseType = "text";
reader.send();
function main()
{
nameslist = reader.responseText.split('\n'); nameslist = nameslist.filter(function(n){return n;}).sort();
console.log("Elements read: " + nameslist.length);
// Additional code to be run after the load is complete goes in this block, starting at this line.
}
Upvotes: 1