How to read a local text file?

前端 未结 20 2131
北恋
北恋 2020-11-21 05:28

I’m trying to write a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.

相关标签:
20条回答
  • 2020-11-21 05:52

    I know, I am late at this party. Let me show you what I have got.

    This is a simple reading of text file

    var path = "C:\\path\\filename.txt"
    var fs = require('fs')
    fs.readFile(path , 'utf8', function(err, data) {
      if (err) throw err;
      console.log('OK: ' + filename);
      console.log(data)
    });
    

    I hope this helps.

    0 讨论(0)
  • 2020-11-21 05:53

    You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver)

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    

    And specify file:// in your filename:

    readTextFile("file:///C:/your/path/to/file.txt");
    
    0 讨论(0)
  • 2020-11-21 05:55

    Visit Javascripture ! And go the section readAsText and try the example. You will be able to know how the readAsText function of FileReader works.

        <html>
        <head>
        <script>
          var openFile = function(event) {
            var input = event.target;
    
            var reader = new FileReader();
            reader.onload = function(){
              var text = reader.result;
              var node = document.getElementById('output');
              node.innerText = text;
              console.log(reader.result.substring(0, 200));
            };
            reader.readAsText(input.files[0]);
          };
        </script>
        </head>
        <body>
        <input type='file' accept='text/plain' onchange='openFile(event)'><br>
        <div id='output'>
        ...
        </div>
        </body>
        </html>
    
    0 讨论(0)
  • 2020-11-21 05:55

    Provably you already try it, type "false" as follows:

     rawFile.open("GET", file, false);
    
    0 讨论(0)
  • 2020-11-21 05:58

    Modern solution:

    Use fileOrBlob.text() as follows:

    <input type="file" onchange="this.files[0].text().then(t => console.log(t))">
    

    When user uploads a text file via that input, it will be logged to the console. Here's a working jsbin demo.

    Here's a more verbose version:

    <input type="file" onchange="loadFile(this.files[0])">
    <script>
      async function loadFile(file) {
        let text = await file.text();
        console.log(text);
      }
    </script>
    

    Currently (January 2020) this only works in Chrome and Firefox, check here for compatibility if you're reading this in the future: https://developer.mozilla.org/en-US/docs/Web/API/Blob/text

    On older browsers, this should work:

    <input type="file" onchange="loadFile(this.files[0])">
    <script>
      async function loadFile(file) {
        let text = await (new Response(file)).text();
        console.log(text);
      }
    </script>
    

    Related: As of September 2020 the new Native File System API available in Chrome and Edge in case you want permanent read-access (and even write access) to the user-selected file.

    0 讨论(0)
  • 2020-11-21 05:58
    <html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {            
                    $.ajax({`enter code here`
                        url: "TextFile.txt",
                        dataType: "text",
                        success: function (data) {                 
                                var text = $('#newCheckText').val();
                                var str = data;
                                var str_array = str.split('\n');
                                for (var i = 0; i < str_array.length; i++) {
                                    // Trim the excess whitespace.
                                    str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
                                    // Add additional code here, such as:
                                    alert(str_array[i]);
                                    $('#checkboxes').append('<input type="checkbox"  class="checkBoxClass" /> ' + str_array[i] + '<br />');
                                }
                        }                   
                    });
                    $("#ckbCheckAll").click(function () {
                        $(".checkBoxClass").prop('checked', $(this).prop('checked'));
                    });
            });
        </script>
    </head>
    <body>
        <div id="checkboxes">
            <input type="checkbox" id="ckbCheckAll" class="checkBoxClass"/> Select All<br />        
        </div>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题