-2

I am trying to write a JavaScript program that reads a local txt file and Safes the Content into an Array. (just an offline JavaScript) I already tried many different methods, but None of them is working:

The activeXObject solution is not working. Server based php Code is not working. FileReader API is not working.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • Possible dublicate of https://stackoverflow.com/questions/14446447/javascript-read-local-text-file – Ayaz Ali Shah Jul 13 '17 at 06:40
  • I also saw this link above and tried all the possibilities, but None of them is working for me!! – helloimthomas Jul 13 '17 at 06:45
  • why is there a css tag? – Jaromanda X Jul 13 '17 at 06:45
  • are you trying to write a web page that reads a file from an end users computer without any interaction from the user? if so, you can't do that. You can only read a file the user wishes you to read (drag/drop or file picker type thing) – Jaromanda X Jul 13 '17 at 06:46
  • I'm trying to read a local text file only by having the filepath. Is that not possible in JavaScript? :/ – helloimthomas Jul 13 '17 at 06:48
  • Basically when i click a specific button on the html page, the program should read the Content of a .txt file in an Array in the Background just to have some Information (that i Need). – helloimthomas Jul 13 '17 at 06:50
  • 1
    Possible duplicate of [Javascript - read local text file](https://stackoverflow.com/questions/14446447/javascript-read-local-text-file) – Skipper Jul 13 '17 at 06:50
  • You need to tell us more about your environment. Is your code running in a browser, on a server (node.js), or some other environment? – Derek 朕會功夫 Jul 13 '17 at 06:53
  • my Code is running in a browser. I'm working on a file Manager and i came to the solution that reading a Textfile, where some paths are saved, is the best Option. – helloimthomas Jul 13 '17 at 06:55
  • But if you have a non-server-based solution for reading all file-names in a local Directory on my PC (preferable with javascript) and print them out on the html page..... then please let me know. – helloimthomas Jul 13 '17 at 06:57

1 Answers1

1

Try this:

<script type="text/javascript">
    function readFile(file){

        if(file.files && file.files[0]){
            var reader = new FileReader();

            reader.onload = function (e) {  
                var input = e.target.result;
                var output = input.split("\n").filter(/./.test, /\@/).join("\n");

                document.getElementById('main').innerHTML = output;
            };
            reader.readAsText(file.files[0]);
        }
    }
</script>
Torsten Walter
  • 5,614
  • 23
  • 26
pr191ex
  • 88
  • 1
  • 14