530

I’m trying to implemennt 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.

function readTextFile() {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "testing.txt", true);
  rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4) {
      var allText = rawFile.responseText;
      document.getElementById("textSection").innerHTML = allText;
    }
  }
  rawFile.send();
}

What is going wrong here?

This still doesn’t seem to work after changing the code a little bit from a previous revision and now it's giving me an XMLHttpRequest exception 101.

I’ve tested this on Firefox and it works, but in Google Chrome it just won't work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers (especially Chrome)?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Danny
  • 9,199
  • 16
  • 53
  • 75

23 Answers23

398

JS introduced the Fetch API in 2015, which replaced XMLHttpRequest with a much simpler way to get data from URLs. In this case:

fetch("myText.txt")
  .then((res) => res.text())
  .then((text) => {
    // do something with "text"
   })
  .catch((e) => console.error(e));

And since all mordern browsers severely lock down what they can do with direct filesystem access, try not to use file:///. Even if you're "just working locally" there are tons of light weight webservers that you can use (including things like running python -m http.server or npx http-server) so you can load your data using normal http urls.

original answer

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;
        console.log(allText);
       }
    }
  }
  rawFile.send(null);
}

And specify file:// in your filename:

readTextFile("file:///C:/your/path/to/file.txt");
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
Majid Laissi
  • 19,188
  • 19
  • 68
  • 105
  • 4
    I'm actually working on this on a mac, so would I still be specifying the file://?? – Danny Jan 21 '13 at 21:01
  • Something like "file:///tmp/my_file" – Majid Laissi Jan 21 '13 at 21:21
  • Doesn't seem to work I've typed in "file:///User/Danny/Desktop/javascriptWork/testing.txt" but it pops up an alert with nothing in it – Danny Jan 21 '13 at 21:46
  • 18
    try to put `file:///User/Danny/Desktop/javascriptWork/testing.txt` in your browser's url bar and see if you can see the file.. – Majid Laissi Jan 21 '13 at 21:52
  • got it to work on browser, but still printing nothing on the alert – Danny Jan 21 '13 at 21:55
  • are you running you JS in a local html file or on a remote server ? – Majid Laissi Jan 21 '13 at 22:12
  • it's all local. all in one folder nothing else. – Danny Jan 21 '13 at 22:37
  • that's strange... can you use jQuery for that? – Majid Laissi Jan 21 '13 at 22:42
  • I never used jQuery before, so I have no idea how to do this in jQuery. This is why I was trying to do this all in html/javascript – Danny Jan 22 '13 at 09:45
  • This would fit into a jQuery ajax handler with text being received in success. – James P. Sep 03 '13 at 14:25
  • 24
    it doesn't need to be an absolute path.. this worked for me just fine: readTextFile('Properties/version.txt'); thanks! – Sonic Soul Apr 17 '14 at 00:08
  • 1
    I am facing exact same problem. Not working for me too even if I add file:/// when I am working in my local using no server at all. – Srijani Ghosh Jul 23 '15 at 08:20
  • 2
    Since we are reading from a webserver, we should have async set to `true`. If this were a simple `local` search then setting async to `false` is ok, but `onreadystatechange` is not needed while it is set to false. Here is the documentation: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp – Michael Ramos Aug 16 '15 at 20:25
  • 202
    This won't work in Chrome (possiblity other browsers) you will get "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource." – Rick Burgess Oct 26 '15 at 11:31
  • 3
    Does this really work without user interaction? I can't get it to work in chrome (without the user choosing the file). – Xan-Kun Clark-Davis Jul 08 '16 at 08:30
  • How can one return a value from this? I can get the text from the file to show up in an alert, or in console.log, but I can't seem to return it. console.log(allText.split("\n")); //This works return allText.split("\n"); //This doesn't (undefined) – james Burns Sep 09 '16 at 12:59
  • 2
    I'm getting a warning that says this is deprecated :/ any recommendations on an alternative method? – Zypps987 Jul 21 '17 at 16:18
  • anyone know if this will work in IE 10 and above... or Edge? It works in firefox – rikkitikkitumbo Nov 28 '17 at 15:08
  • @RickBurgess You need to run the code in apache server, it works. – Janice Zhong Sep 23 '18 at 17:43
  • 1
    I am getting `Access is denied.`. My browser is IE11. Any suggestions ? – Karthik Sep 27 '18 at 08:53
  • 2
    Didn't work in Chrome. FireFox also threw an error: `Synchronous XMLHttpRequest on the main thread is deprecated` – attacomsian May 18 '19 at 08:30
  • Seems to work in Chrome now. I think generally async (3d parameter in `open()`) should be set to true. – hBrent Aug 20 '19 at 15:25
  • 2
    To all users who need a good answer: `fetch("myText.txt", {mode: "no-cors"}).then(res => res.text()).then(text => doSomethingWithText(text))` – Angshu31 May 24 '20 at 19:44
  • 1
    how is that a good answer index.html:13 Fetch API cannot load file:///C:/un/job/plugin_reader/debug. URL scheme "file" is not supported. – user151496 May 28 '20 at 14:00
  • @user151496 maybe because it was answered 7 years ago ? – Majid Laissi Jun 20 '20 at 19:16
  • What is base path? – mathtick Dec 31 '20 at 13:28
  • This is really useful! I'm using it with JSZip to move contents of an scss file into a new file within the zip. – Dan Canetti Mar 03 '21 at 23:55
  • For anyone getting CORS error -- try to run the file on live/development server. It won't work if you directly open the HTML file in the browser. – Aniket Kariya May 08 '21 at 17:09
  • I want to read local image file as dataURL, how can i do that? – yog Jan 11 '22 at 08:23
  • Dany (OP) requested opening a local file not on a server side, so why a reply with a wrong solution to initial question got so many upvotes? Solution simply does not work due to CORS violations. And a comment by @Rick Burgess here highlight this and received 202 upvotes but original response here didn't receive -202 downvotes? – LXSoft Aug 09 '23 at 17:10
198

After the introduction of fetch api in javascript, reading file contents could not be simpler.

reading a text file

fetch('file.txt')
  .then(response => response.text())
  .then(text => console.log(text))
  // outputs the content of the text file

reading a json file

fetch('file.json')
  .then(response => response.json())
  .then(jsonResponse => console.log(jsonResponse))     
   // outputs a javascript object from the parsed json

Update 30/07/2018 (disclaimer):

This technique works fine in Firefox, but it seems like Chrome's fetch implementation does not support file:/// URL scheme at the date of writing this update (tested in Chrome 68).

Update-2 (disclaimer):

This technique does not work with Firefox above version 68 (Jul 9, 2019) for the same (security) reason as Chrome: CORS request not HTTP. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp.

OlivierM
  • 2,820
  • 24
  • 41
Abdelaziz Mokhnache
  • 4,269
  • 3
  • 25
  • 35
  • 4
    Brilliant! Quoting the Fetch Standard: "provides consistent handling of: URL schemes, Redirects, Cross-origin semantics, CSP, Service workers, Mixed Content, `Referer`". I guess this means goodbye to good ol'FileReaders and HttpRequests (and I won't miss them a bit ;) – Armfoot Oct 25 '17 at 17:17
  • 3
    But how can you use the *text* and put it into a string variable for use elsewhere? (I keep on getting 'undefined' no matter what I do to it.) – not2qubit Feb 08 '18 at 08:03
  • 2
    @not2qubit fetching a text file is an async operation. You are getting undefined because you are using the variable before the file is completely read. You have to use it inside the promise callback or use something like javascript "async await" operators. – Abdelaziz Mokhnache Feb 08 '18 at 12:45
  • 39
    `Fetch API cannot load file:///C:/Users/path/to/file/file.txt. URL scheme must be "http" or "https" for CORS request.` – J-Cake Jun 07 '18 at 02:21
  • 2
    same here stupid Chrome 68. I can't believe this is a hot topic, thanks @AbdelazizMokhnache keep us informed. JAK. I just tested File-Save.js, it works, and I want something simple to read the file back (basically save/restore my settings to a file of my choice) – Meryan Jul 31 '18 at 06:44
  • 1
    browser compatibility: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#Browser_compatibility – Sam Murphy May 24 '19 at 10:35
  • Actually it is not possible with Firefox since version 68 (July 2019) to read local file using `fetch` for the same (security) reason as Chrome: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp – OlivierM Feb 22 '20 at 10:16
  • If you upload your script with your text file it solves the URL scheme problem. A little bit of an annoying process, but it seems to still be far easier than XMLRequests – Ethan Moore Apr 14 '20 at 18:22
  • file.uri.strict set to false if you want to read local files inside your project dir – Bhikkhu Subhuti Jun 20 '20 at 14:00
  • to enable fetch in chrome - put the files you want to expose in the assets folder (or any equivalent folder) – mamashare Jun 01 '21 at 11:17
  • It works for me in Firefox 88 but not in Chrome 94. – Jose Manuel Abarca Rodríguez Oct 07 '21 at 15:57
139

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

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]);
};
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>
  ...
</div>
Teocci
  • 7,189
  • 1
  • 50
  • 48
Amit Chaurasia
  • 1,529
  • 2
  • 11
  • 8
  • 21
    Links are nice, but you should "always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline." See [How do I write a good answer](https://stackoverflow.com/help/how-to-answer). – 4ae1e1 Mar 20 '15 at 22:04
  • 25
    This example deals with a user-input text file, but I think the question was about a file that's local to the server. – S. Kirby Sep 05 '15 at 17:42
  • 3
    @S.Kirby As said by the OP in response to a question about if it's run locally or on a remote server: [it's all local. all in one folder nothing else.](https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file#comment20120579_14446538). Besides, other people (like me) might have the question about how to do it locally. – Simon Forsberg Nov 26 '19 at 13:10
  • This solution automatically reads the content of the selected file which I like it. I wanted to make it to work like on urltodomain.com (in a textarea), but it initially failed because of this: `node.innerText = text;` (the script populated the contents but within the – Tomasz Feb 16 '23 at 14:02
57

var input = document.getElementById("myFile");
var output = document.getElementById("output");


input.addEventListener("change", function () {
  if (this.files && this.files[0]) {
    var myFile = this.files[0];
    var reader = new FileReader();
    
    reader.addEventListener('load', function (e) {
      output.textContent = e.target.result;
    });
    
    reader.readAsBinaryString(myFile);
  }   
});
<input type="file" id="myFile">
<hr>
<textarea style="width:500px;height: 400px" id="output"></textarea>
Poornachander K
  • 603
  • 5
  • 4
  • 20
    I'm not sure this answers this 4 year old question. The OP isn't uploading documents, they are trying to read the text file in the same directory from a path. And if you're going to answer questions this old at least write a short summary of why you think your answer is now better than the others or how the language has changed since the question to warrant a new answer. – Matthew Ciaramitaro Aug 22 '17 at 14:23
  • 4
    Using my own existing file upload input html - copying the lines from `var reader = new FileReader();` through `reader.readAsBinaryString(..)` - it reads the contents of my text file. Clean, elegant, works like a charm. Best answer in this thread for me - thanks! – Gene Bo May 08 '18 at 18:28
  • How to get the file name? – Random Kindle Mar 10 '22 at 12:17
39

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.

joe
  • 3,752
  • 1
  • 32
  • 41
36

Yes JS can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html <input type="file">.

Then with JS it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.

What JS cannot do for security reasons is to access automatically (without the user input) to the filesystem of his computer.

To allow JS to access to the local fs automatically is needed to create not an html file with JS inside it but an hta document.

An hta file can contain JS or VBS inside it.

But the hta executable will work on windows systems only.

This is standard browser behavior.

Also Google Chrome worked at the fs API, more info here: http://www.html5rocks.com/en/tutorials/file/filesystem/

isherwood
  • 58,414
  • 16
  • 114
  • 157
Sparrow
  • 361
  • 3
  • 3
16

Using Fetch and async function

const logFileText = async file => {
    const response = await fetch(file)
    const text = await response.text()
    console.log(text)
}

logFileText('file.txt')
barro32
  • 2,559
  • 23
  • 36
12

Try creating two functions:

function getData(){       //this will read file and send information to other function
       var xmlhttp;

       if (window.XMLHttpRequest) {
           xmlhttp = new XMLHttpRequest();               
       }           
       else {               
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");               
       }

       xmlhttp.onreadystatechange = function () {               
           if (xmlhttp.readyState == 4) {                   
             var lines = xmlhttp.responseText;    //*here we get all lines from text file*

             intoArray(lines);     *//here we call function with parameter "lines*"                   
           }               
       }

       xmlhttp.open("GET", "motsim1.txt", true);
       xmlhttp.send();    
}

function intoArray (lines) {
   // splitting all text data into array "\n" is splitting data from each new line
   //and saving each new line as each element*

   var lineArr = lines.split('\n'); 

   //just to check if it works output lineArr[index] as below
   document.write(lineArr[2]);         
   document.write(lineArr[3]);
}
Bill Bell
  • 21,021
  • 5
  • 43
  • 58
Motsim Mansoor
  • 129
  • 1
  • 3
12

Probably you already tried it, but type "false" as follows:

     rawFile.open("GET", file, false);
Osmar
  • 198
  • 9
momen
  • 129
  • 1
  • 3
11

other example - my reader with FileReader class

<html>
    <head>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
        <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
    </head>
    <body>
        <script>
            function PreviewText() {
            var oFReader = new FileReader();
            oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
            oFReader.onload = function (oFREvent) {
                document.getElementById("uploadTextValue").value = oFREvent.target.result; 
                document.getElementById("obj").data = oFREvent.target.result;
            };
        };
        jQuery(document).ready(function(){
            $('#viewSource').click(function ()
            {
                var text = $('#uploadTextValue').val();
                alert(text);
                //here ajax
            });
        });
        </script>
        <object width="100%" height="400" data="" id="obj"></object>
        <div>
            <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
            <input id="uploadText" style="width:120px" type="file" size="10"  onchange="PreviewText();" />
        </div>
        <a href="#" id="viewSource">Source file</a>
    </body>
</html>
websky
  • 3,047
  • 1
  • 33
  • 31
5

This might help,

    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    }

    xmlhttp.open("GET", "sample.txt", true);
    xmlhttp.send();
Sameera R.
  • 4,384
  • 2
  • 36
  • 53
4

This question may be old but there two main ideas that we need to clarify. Do we want to read the whole file at once? or read it line by line?

Teo, I want to get the whole file and process it later.

Okay, that is very easy. We just need to call Blob.text() method (remember that this method assumes that the file is encoded as UTF-8) and handle the file like this:

const $output = document.getElementById('output')
const $file = document.getElementById('file')
const fetchFile = async e => {
  const [file] = e.target.files
  const text = await file.text()
  $output.textContent = text
}

$file.onchange = fetchFile
<input id='file' type='file' accept='text/plain'><br>
<pre id='output'>...</pre>

What about line by line? Is that possible?.

Yes my young Padawan, that is also possible. We just need to call the String.split() method to divide the text into an array of lines like this:

const $output = document.getElementById('output')
const $file = document.getElementById('file')
let count
const fetchFile = async e => {
  const [file] = e.target.files
  if (!file) return
  count = 0
  const text = await file.text()
  $output.textContent = text

  const lines = text.split(/\r?\n/gm)
  for (const line of lines) {
    if (line) count++
  }
  console.log({count})
}

$file.onchange = fetchFile
<input id='file' type='file' accept='text/plain'><br>
<pre id='output'>...</pre>
Teocci
  • 7,189
  • 1
  • 50
  • 48
  • Best answer so far! Thank you. – Abednego Nasila Jun 15 '23 at 08:06
  • @Teocci Good example, I would like to understand how CORS violation policy is not happening in this example? – LXSoft Aug 09 '23 at 17:40
  • The `CORS policy` is a security feature that prevents browsers from making cross-origin requests to other servers. This code does not violate the CORS policy because the file is being fetched from the local file system, not from a remote server. – Teocci Aug 10 '23 at 00:10
3

Local AJAX calls in Chrome are not supported due to same-origin-policy.

Error message on chrome is like this: "Cross origin requests are not supported for protocol schemes: http, data, chrome, chrome-extension, https."

This means that chrome creates a virtual disk for every domain to keep the files served by the domain using http/https protocols. Any access to files outside this virtual disk are restricted under same origin policy. AJAX requests and responses happen on http/https, therefore wont work for local files.

Firefox does not put such restriction, therefore your code will work happily on the Firefox. However there are workarounds for chrome too : see here.

Sushant T
  • 31
  • 4
2

Adding to some the above answers, this modified solution worked for me.

<input id="file-upload-input" type="file" class="form-control" accept="*" />

....

let fileInput  = document.getElementById('file-upload-input');
let files = fileInput.files;

//Use createObjectURL, this should address any CORS issues.
let filePath = URL.createObjectURL(files[0]);

....

function readTextFile(filePath){
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", filePath , true);
    rawFile.send(null);

    rawFile.onreadystatechange = function (){
        if(rawFile.readyState === 4){
            if(rawFile.status === 200 || rawFile.status == 0){
                var allText = rawFile.responseText;
                console.log(allText);
            }
        }
    }     
}
Fabii
  • 3,820
  • 14
  • 51
  • 92
2
function readTextFile(file) {
    var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
    rawFile.open("GET", file, false); // open with method GET the file with the link file ,  false (synchronous)
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
        {
            if(rawFile.status === 200) // status 200: "OK"
            {
                var allText = rawFile.responseText; //  Returns the response data as a string
                console.log(allText); // display text on the console
            }
        }
    }
    rawFile.send(null); //Sends the request to the server Used for GET requests with param null
}

readTextFile("text.txt"); //<= Call function ===== don't need "file:///..." just the path 

- read file text from javascript
- Console log text from file using javascript
- Google chrome and mozilla firefox

in my case i have this structure of files : enter image description here

the console.log result :
enter image description here

nadir hamidou
  • 423
  • 2
  • 7
  • 18
  • 2
    Below is the error showing: **Access to XMLHttpRequest at 'file:///C:/{myLocalPath}PropertiesFile.txt' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.** – Kumar Kartikeya Jan 24 '20 at 09:15
2

Get local file data in js(data.js) load:

function loadMyFile(){
    console.log("ut:"+unixTimeSec());
    loadScript("data.js?"+unixTimeSec(), loadParse);
}
function loadParse(){
    var mA_=mSdata.split("\n");
    console.log(mA_.length);
}
function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}
function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*![^\r\n]*[\r\n]*/, "").
      replace(/[\r\n][^\r\n]*\*\/[^\/]+$/, "");
}
function unixTimeSec(){
    return Math.round( (new Date()).getTime()/1000);
}

file of data.js like:

var mSdata = hereDoc(function() {/*!
17,399
1237,399
BLAHBLAH
BLAHBLAH
155,82
194,376
*/});

dynamic unixTime queryString prevents cached.

AJ works in web http://.

Lo Vega
  • 121
  • 1
  • 3
  • why don't you use the ES6 template literal syntax for multiline strings? (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) – Sapphire_Brick May 11 '20 at 15:51
2

How to read a local file?

By using this you will load a file by loadText() then JS will asynchronously wait until the file is read and loaded after that it will execture readText() function allowing you to continue with your normal JS logic (you can also write a try catch block on the loadText() function in the case any error arises) but for this example I keep it at minimal.

async function loadText(url) {
    text = await fetch(url);
    //awaits for text.text() prop 
    //and then sends it to readText()
    readText(await text.text());
}

function readText(text){
    //here you can continue with your JS normal logic
    console.log(text);
}

loadText('test.txt');
D.Snap
  • 1,704
  • 1
  • 22
  • 15
2

If you want to prompt the user to select a file, then read its contents:

// read the contents of a file input
const readInputFile = (inputElement, callback) => {
  const reader = new FileReader();
  reader.onload = () => {
    callback(reader.result)
  };
  reader.readAsText(inputElement.files[0]);
};
// create a file input and destroy it after reading it
const openFile = (callback) => {
  var el = document.createElement('input');
  el.setAttribute('type', 'file');
  el.style.display = 'none';
  document.body.appendChild(el);
  el.onchange = () => {readInputFile(el, (data) => {
    callback(data)
    document.body.removeChild(el);
  })}
  el.click();
}

Usage:

// prompt the user to select a file and read it
openFile(data => {
    console.log(data)
  })
yaya
  • 7,675
  • 1
  • 39
  • 38
1
<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>
adithya
  • 11
  • 1
1

This function made for browsers and open file picker dialog and after user selection read file as binary and call callback function with read data:

function pickAndReadFile(callback) {
    var el = document.createElement('input');
    el.setAttribute('type', 'file');
    el.style.display = 'none';
    document.body.appendChild(el);
    el.onchange = function (){
        const reader = new FileReader();
        reader.onload = function () {
            callback(reader.result);
            document.body.removeChild(el);
        };
        reader.readAsBinaryString(el.files[0]);
    }
    el.click();
}

And use it like this:

pickAndReadFile(data => {
  console.log(data)
})
MSS
  • 3,520
  • 24
  • 29
0

You can import my library:

<script src="https://www.editeyusercontent.com/preview/1c_hhRGD3bhwOtWwfBD8QofW9rD3T1kbe/code.js?pe=yikuansun2015@gmail.com"></script>

then, the function fetchfile(path) will return the uploaded file

<script src="https://www.editeyusercontent.com/preview/1c_hhRGD3bhwOtWwfBD8QofW9rD3T1kbe/code.js"></script>
<script>console.log(fetchfile("file.txt"))</script>

Please note: on Google Chrome if the HTML code is local, errors will appear, but saving the HTML code and the files online then running the online HTML file works.

0

In order to read a local file text through JavaScript using chrome, the chrome browser should run with the argument --allow-file-access-from-files to allow JavaScript to access local file, then you can read it using XmlHttpRequest like the following:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
   if (xmlhttp.readyState == 4) {
       var allText = xmlhttp.responseText;          
            }
        };
xmlhttp.open("GET", file, false);
xmlhttp.send(null);
Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17
-1

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.

Aljohn Yamaro
  • 2,629
  • 25
  • 22
  • 4
    You should *quote* the file path. Moreover, his code uses the DOM library, implying that he meant vanilla JavaScript, not node.js. – Sapphire_Brick Jul 06 '20 at 18:11