问题
Is there any way to read a file line by line in javascript, specifically this file which is a dictionary. I was trying to build a replica of a java anagram solver I made a few months ago, but hit this problem of not being able to read a file line by line. I could download the file and store it locally if that would make any difference to being able to read it.
回答1:
Use YQL:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fdocs.oracle.com%2Fjavase%2Ftutorial%2Fcollections%2Finterfaces%2Fexamples%2Fdictionary.txt%22&format=json&diagnostics=true&callback=cbfunc
Here's what the fiddle looks like:
window.callback = function(a) { window.file = a.query.results.body.p; go(); };
$.getScript('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fdocs.oracle.com%2Fjavase%2Ftutorial%2Fcollections%2Finterfaces%2Fexamples%2Fdictionary.txt%22&format=json&diagnostics=true&callback=callback');
window.go = function() {
var terms = file.split(' ');
for (var i = 0; i < 100; i++)
console.log(terms[i])
};
The fiddle only does the first 100 but you get the idea (I hope).
回答2:
In most circumstances, you could just read the file into memory and then parse it into lines. If you read the whole thing into memory with an ajax call, you could just use data.split("\n")
to convert it to an array of lines.
回答3:
You should initiate Ajax Request for such Operation. Reading a file line by line although is not recommended via Ajax, as you will end up create loads of server requests in the process;as JavaScript is all about Client side and limited access also. Ajax request to server is recent years add-on to it.
Definitely you are searching some information using some keywords; so it would be wise if you add the search logic on server functions; call the specific function via Ajax and return back result-set to the browser. That function could be a file that generates result or, a web service. You choose your flavor.
Alternate option would be to re-code the file information to JSON (about JSON) at start and let it roll to client js script. I would not recommend XML for this as its gonna eatup loads of browser memory in the processing terms. Been there! :(. Since JavaScript has native support to JSON, it will go smooth. Warning this exposes data to local.
来源:https://stackoverflow.com/questions/9970541/can-you-read-line-by-line-in-javascript