How to read a .txt file from JavaScript?

10

I am new to web development, surely what I am asking is very simple but I can not find a clear solution.

I have a file .txt in the path res/texto.txt , and from a javascript I want to read it to cross it by lines and that.

I need to know how I can read it.

    
asked by arnold 11.03.2017 в 22:01
source

2 answers

11

Depending on the side the file is in, you could proceed in two ways: by reading the file from the client's device (explained in A), or from the server (explained in B).

A. IF THE FILE IS ON THE CLIENT'S SIDE

You can do it using FileReader . The client must select the file by clicking on the button:

function leerArchivo(e) {
  var archivo = e.target.files[0];
  if (!archivo) {
    return;
  }
  var lector = new FileReader();
  lector.onload = function(e) {
    var contenido = e.target.result;
    mostrarContenido(contenido);
  };
  lector.readAsText(archivo);
}

function mostrarContenido(contenido) {
  var elemento = document.getElementById('contenido-archivo');
  elemento.innerHTML = contenido;
}

document.getElementById('file-input')
  .addEventListener('change', leerArchivo, false);
<input type="file" id="file-input" />
<h3>Contenido del archivo:</h3>
<pre id="contenido-archivo"></pre>

Note:

This method is compatible with:

  • IE 10 +
  • Firefox 3.6 +
  • Chrome 13 +
  • Safari 6.1 +

B. IF THE FILE IS ON THE SERVER'S SIDE

You can do it with jQuery. In the example, the url of the file is entered in the input and pressing the button requests the file from the server using the get method of Ajax If the answer is satisfactory, the file is displayed on a div.

<script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>

<script>
$(function() 
{
$("#button").click( function()
{
   //var TXT_URL = 'https://www.mozilla.org/media/MPL/2.0/index.815ca599c9df.txt';
   var TXT_URL = $("#input-url").val();

    $.ajax
    (
    	{
        	url : TXT_URL,
			dataType: "text",
			success : function (data) 
			{
            	$(".text").html("<pre>"+data+"</pre>");
			}
		}
	);
   });
});

</script>
Ingrese una url válida:<input type="text" id="input-url" size="50" value="https://www.mozilla.org/media/MPL/2.0/index.815ca599c9df.txt"></input>

<input type="button" id="button" value="Ver .txt"></input>
<div class="text">
  <hr />
  <h2>Texto:</h2>
</div>
    
answered by 11.03.2017 в 23:56
2
  

I have a .txt file in the path res / texto.txt, and from a javascript I want to read it to go through it by lines.

If the file is on the server, simply use AJAX:

fetch('/res/texto.txt')
  .then(res => res.text())
  .then(content => {
    let lines = content.split(/\n/);
    lines.forEach(line => console.log(line));
  });

If the file should be uploaded by the client, then you need the File API:

let area = document.getElementById('area');

area.addEventListener('dragover', e => e.preventDefault());
area.addEventListener('drop', readFile);

function readFile (e) {
  e.preventDefault();
  let file = e.dataTransfer.files[0];
  
  if (file.type === 'text/plain') {
    let reader = new FileReader();
    reader.onloadend = () => printFileContents(reader.result);
    reader.readAsText(file, 'ISO-8859-1');
  } else {
    alert('¡He dicho archivo de texto!');
  }
}

function printFileContents (contents) {
  area.style.lineHeight = '30px';
  area.textContent = '';
  let lines = contents.split(/\n/);

  lines.forEach(line => area.textContent += line + '\n');
}
@import url('https://fonts.googleapis.com/css?family=Noto+Sans');

*, *:before, *:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Noto Sans';
}

#area {
  align-items: center;
  border: 3px dashed #aaa;
  border-radius: 5px;
  color: #555;
  display: flex;
  flex-flow: column nowrap;
  font-size: 15px;
  height: 80vh;
  justify-content: center;
  max-height: 400px;
  margin: 30px auto;
  overflow: auto;
  padding: 25px;
  text-align: center;
  white-space: pre-line;
  width: 80%;
  max-width: 600px;
}

h3 {
  color: #555;
  font-weight: 400;
}
<div id="area">
  <h3>Suelta un archivo de texto y mira qué pasa ;)</h3>
</div>
    
answered by 12.03.2017 в 14:26