How to load a text file in JavaScript?

I am creating a simple WebGL project and need a loading method in the model. I decided to use the OBJ format, so I need a way to download it. The file (will) be stored on the server, and my question is: how does one of the JS load into a text file and scan it line by line, token using a token (for example, with streams in C ++)? I am new to JS, so my question is. The simpler the better.

UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I am loading data from a file into the forEach loop that you wrote, but outside of it (that is, after all your code), the object that I filled with data has "undefined". What am I doing wrong? Here is the code:

var materialFilename; function loadOBJModel(filename) { // ... var req = new XMLHttpRequest(); req.open('GET', filename); req.responseType = 'text'; req.onreadystatechange = function() { if (req.readyState == 4) { var lines = req.responseText.split(/\n/g); lines.forEach(function(line) { readLine(line); }); } } req.send(); alert(materialFilename); // ... } function readLine(line) { // ... else if (tokens[0] == "mtllib") { materialFilename = tokens[1]; } // ... } 
+4
source share
2 answers

You can use XMLHttpRequest to extract the file, assuming it comes from the same domain as your main web page. If not, and you have control over the server where your file is located, you can enable CORS without any problems. For instance.

To scan line by line, you can use split (). For instance. Something like that...

 var req = new XMLHttpRequest(); req.open('GET', '/your/url/goes/here'); req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status == 200) { var lines = req.responseText.split(/\n/g); lines.forEach(function(line, i) { // 'line' is a line of your file, 'i' is the line number (starting at 0) }); } else { // (something went wrong with the request) } } } req.send(); 
+3
source

If you can’t just load the data from XHR or CORS, you can always use the JSON-P method, surrounding it using the JavaScript function and dynamically attaching the script tag to the page.

You will have a server-side script that takes a callback parameter and returns something like callback1234(/* file data here */); .

Once you have the data, the parsing should be trivial, but you will have to write your own parsing functions. Nothing exists for this.

0
source

All Articles