Reading file txt

Hi, I have these 3 codes That read txt files

    <output id="files"></output>
            <script type="text/javascript" src=""></script>
<script type="text/javascript">
$(function () {
    $("#upload").bind("click", function () {
        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
        if (regex.test($("#fileUpload").val().toLowerCase())) {
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var table = $("<table />");
                    var rows ="\n");
                    for (var i = 0; i < rows.length; i++) {
                        var row = $("<tr />");
                        var cells = rows[i].split(".");
                        for (var j = 0; j < cells.length; j++) {
                            var cell = $("<td />");
            } else {
                alert("This browser does not support HTML5.");
        } else {
            alert("Please upload a valid CSV file.");
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
<meta charset="utf-8" />
<title>Demo - CSV-to-Table</title>
  <div id="inputs" class="clearfix">
    <input type="file" id="files" name="files[]" multiple />
  <hr />
  <output id="list">
  <hr />
  <table id="contents" style="width:100%; height:400px;" border>
  <script src=""></script>
  <script src=""></script>
    $(document).ready(function() {
      if(isAPIAvailable()) {
        $('#files').bind('change', handleFileSelect);
    function isAPIAvailable() {
      // Check for the various File API support.
      if (window.File && window.FileReader && window.FileList && window.Blob) {
        // Great success! All the File APIs are supported.
        return true;
      } else {
        // source: File API availability -
        // source: <output> availability -
        document.writeln('The HTML5 APIs used in this form are only available in the following browsers:<br />');
        // 6.0 File API & 13.0 <output>
        document.writeln(' - Google Chrome: 13.0 or later<br />');
        // 3.6 File API & 6.0 <output>
        document.writeln(' - Mozilla Firefox: 6.0 or later<br />');
        // 10.0 File API & 10.0 <output>
        document.writeln(' - Internet Explorer: Not supported (partial support expected in 10.0)<br />');
        // ? File API & 5.1 <output>
        document.writeln(' - Safari: Not supported<br />');
        // ? File API & 9.2 <output>
        document.writeln(' - Opera: Not supported');
        return false;
    function handleFileSelect(evt) {
      var files =; // FileList object
      var file = files[0];
      // read the file metadata
      var output = ''
          output += '<span style="font-weight:bold;">' + escape( + '</span><br />\n';
          output += ' - FileType: ' + (file.type || 'n/a') + '<br />\n';
          output += ' - FileSize: ' + file.size + ' bytes<br />\n';
          output += ' - LastModified: ' + (file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() : 'n/a') + '<br />\n';
      // read the file contents
      // post the results
    function printTable(file) {
      var reader = new FileReader();
      reader.onload = function(event){
        var csv =;
        var data = $.csv.toArrays(csv);
        var html = '';
        for(var row in data) {
          html += '<tr>\r\n';
          for(var item in data[row]) {
            html += '<td>' + data[row][item] + '</td>\r\n';
          html += '</tr>\r\n';
      reader.onerror = function(){ alert('Unable to read ' + file.fileName); };
<!DOCTYPE html>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <title> by bruiz</title>
var leitorDeCSV = new FileReader();
window.onload = function init() {
    leitorDeCSV.onload = leCSV;
function pegaCSV(inputFile) {
    var file = inputFile.files[0];
function leCSV(evt) {
    var fileArr ='\n');
    var strDiv = '<table>';
    for (var i=0; i<fileArr.length; i++) {
        strDiv += '<tr>';
        var fileLine = fileArr[i].split('.');
            for (var j=0; j<fileLine.length; j++) {
                strDiv += '<td>'+fileLine[j].trim()+'</td>';
        strDiv += '</tr>';
    strDiv += '</table>';
    var CSVsaida = document.getElementById('CSVsaida');
        CSVsaida.innerHTML = strDiv;
    <input type="file" id="inputCSV" onChange="pegaCSV(this)">
    <div id="CSVsaida"></div>

These 3 code work perfectly, I want to execute the select file executing automatic file in onload or any other form since it automatically runs in index.html and already open the file data.txt,
Data.txt file and the following
The variable var1 = first line of the data.txt file
Var2 second line of file data.txt
Var3 third line of data.txt file

How could I do that ???

Why do you want each line as a separate variable?

You already have each line as an item in the fileArr that is much more easily consumed than separate named variables. fileArr[0] fileArr[1] etc.

How do I open file data.txt with the file path, c:\test\data.txt???

From “c:/” ?

If you mean your computer instead of a website (live or localhost) then you are going to have security permission problems. At least for browser JavaScript.

And read data.txt file where the index.html and other site files are hosted in the same location

I think I missed your question.

You cannot read from a file without the user having select it in an <input>
Your first example is the only way.

I do not understand the 3 examples I have to select the file to open it, I want to not need to select file, open file by name data.txt understood, open file by file path without having to select how can I do ???

^^ You cannot read from a file without the user having select it in an <input>

Browsers prevent you from accessing the filesystem without the users consent by selecting a file.

When I opened google chrome I want to read the file data.txt how could I do it would have some code to send me ???

To me it’s a lot easier to open text files in a text editor.

But if you want to open them in your Chrome browser (this is for Windows, but I imagine other OS have similar)

  • navigate to the text file
  • right click
  • open with
  • navigate to your Chrome.exe file

Is not this I want to run JavaScript in Google Chrome, the javascript function will automatically read the data.txt file, the above 3 JavaScript example read the file however I have to select the file that will be read, need to read through the JavaScript automatic data.txt Without always having to select the file

This works for me


Just a simple txt file with some text. 

This file is for testing with the xhr-test.html file.


<html lang="en">
<title>XHR Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<h1>XHR Test</h1>
  <button id="request_button">Request File</button>
<div id="response_div"></div>
<script type="application/javascript">
var request_button = document.getElementById("request_button");
var filename = "example-txt-file.txt";

request_button.addEventListener('click', function(evt) {

function request_file(filename) {
  var request_obj = new XMLHttpRequest();
  request_obj.responseType = 'text';"GET", filename);
  request_obj.onload = function () {

function display_response(content) {
  var response_div = document.getElementById("response_div");
  response_div.textContent = content;

Both files in the same folder on my localhost server

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.