Search code examples
javascriptfilereaderfile-read

Can you read line by line in javascript?


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.


Solution

  • 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).