read flat file txt with javascript

Technology

read flat file txt with javascript

how to read a flat text file hosted from the server with javascript only line by line

read flat file txt with javascript
Read flat file txt with javascript



welcome to mbajava the website where you learn to program step by step, in this class you will learn to read a flat file txt only using javascript, as online security can not read a file without first being loaded by the visitor, then we must have a flat file on the server which will load your content line by line, eliminating annoying line breaks,
the first is that we should create a notebook called mbajava.txt and we will add any content


therefore we create a .js and javascript file where we place the code that will be responsible for reading this flat file mba.js





var arrayData = new Array();
var archivoTxt = new XMLHttpRequest();
var fileRuta = 'mbajava.txt';
var dataSum = 0;
var tami=0;
var tamj=0;

archivoTxt.open("GET", fileRuta, false);
archivoTxt.send(null);
var txt = archivoTxt.responseText;
//console.log("" + txt + "");
//alert(txt);



var lines = txt.split("\n");
for (var n = 0; n < lines.length; n++)
{
    var line = lines[n];
    console.log(line);
}


We use XMLHttpRequest to load the flat file and get the answer or content.

of course we must have an html file to execute the javascript, we create an html file next to it called mba.html







<!DOCTYPE html>
<!--
https://www.mbajava.com/
-->
<html>
    <head>
         <script src="mba.js"></script>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>TODO write content</div>
    </body>
</html>

execute this html file in the browser, and in the navigator for example chrome we type f12 to see the results by console:


how to read a flat text file hosted from the server with javascript only line by line


Post a Comment

0 Comments