How to load a text file in JavaScript?

元气小坏坏 提交于 2019-12-10 15:26:17

问题


I'm creating a simple WebGL project and need a way to load in models. I decided to use OBJ format so I need a way to load it in. The file is (going to be) stored on the server and my question is: how does one in JS load in a text file and scan it line by line, token by token (like with streams in C++)? I'm new to JS, hence my question. The easier way, the better.

UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I load the data from a file in forEach loop you wrote but outside of it (i.e. after all your code) the object I've been filling data with is "undefined". What am I doing wrong? Here's 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];
    }

    // ...
}

回答1:


You can use XMLHttpRequest to fetch the file, assuming it's coming from the same domain as your main web page. If not, and you have control over the server hosting your file, you can enable CORS without too much trouble. E.g.

To scan line-by-line, you can use split(). E.g. Something like this ...

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();



回答2:


If you can't simply load the data with XHR or CORS, you could always use the JSON-P method by wrapping it with a JavaScript function and dynamically attaching the script tag to your page.

You would have a server-side script that would accept a callback parameter, and return something like callback1234(/* file data here */);.

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



来源:https://stackoverflow.com/questions/13574930/how-to-load-a-text-file-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!