Set a text file on the server to be read every time you run . html (with embedded Javascript language)

Asked

Viewed 411 times

1

I need the browser to return me pre-registered information of people and their addresses, where each one has two houses on the same street.

To do so, I simulated a server in my pc folder, and thus created a.txt data file in the same directory as a . html file.

In the.txt data file I wrote the following data, to be used by the system as a database:

[item]|1|Danilo|13057423|1|200| [item]|2|Denise|13059778|200|500| [item]|3|Guilherme|13052445|500|1000|

In this data, I’m trying to get the system to recognize that Danilo has two houses in CEP 13057423, number 1 and 200. And Denise the same way, and so on.

So, I researched how to make the system read this information and return the data to me automatically, but only found a way where I would have to, every time I need the data, have to upload the file, as you can see in the code that follows:

<html>
<body>
	<head>
		<title>Listando itens de arquivo TXT |</title>
	</head>
 <style type="text/css">
 	#lista{
 		width:50%;
 		border: 1px solid black;
 	 	}
 </style> 
 
<table>
	<tr>
		<div>Escolha um arquivo de texto para carregar:</div>
		<div><input type="file" id="fileToLoad"></div>
		<div><button onClick="loadFileAsText()">Carregar o arquivo selecionado</button><div>
	</tr>
</table>
<table id="lista" border="1">
	<tr>
		<div>Nome</div>
		<div>CEP</div>
		<div>número da casa</div>
		<div>número da casa 2</div>
	</tr>
</table>
<script type='text/javascript'>
function loadFileAsText()
{
	var fileToLoad = document.getElementById("fileToLoad").files[0];

	var fileReader = new FileReader();
	fileReader.onload = function(fileLoadedEvent) 
	{
		var textFromFileLoaded = fileLoadedEvent.target.result;
		var texto = textFromFileLoaded;
		listar(texto);
	};
	fileReader.readAsText(fileToLoad, "UTF-8");
}
function listar(texto){
	var quantidade = document.getElementById("lista").rows.length;
	if (quantidade>1){
		for(var cont=1;cont<=quantidade;cont++){
			document.getElementById("lista").deleteRow(cont);
		}
	}
	var itens = texto.split('[item]');
	for(var i=1;i<itens.length;i++){
		var valores = itens[i].split("|");
		document.getElementById("lista").innerHTML +='<tr><div>'+valores[1]+'</div><div>'+valores[2]+'</div><div>'+valores[3]+'</div><div>'+valores[4]+'</div></tr>';
	}
}
</script>
</body>
</html>

Now, my goal is to get the system to load the file automatically, without me having to "upload" it every time I need the system to return information to me in the browser.

I did a lot of research, and I was able to find some information on how to do this. I made the changes to the code and it was as follows:

<html>
<body>
	<head>
		<title>Listando itens de arquivo TXT |</title>
	</head>
 <style type="text/css">
 	#lista{
 		width:50%;
 		border: 1px solid black;
 	 	}
 </style> 
 
<table>
	<tr>
		<iframe id="fileToLoad" src="dados.txt" style="display: none;"></iframe>
		<div><button onClick="loadFileAsText()">Mostrar as informações de Nome, CEP, número da casa 1 e 2</button><div>
	</tr>
</table>
<table id="lista" border="1">
	<tr>
		<div>Nome</div>
		<div>CEP</div>
		<div>número da casa</div>
		<div>número da casa 2</div>
	</tr>
</table>
<script type='text/javascript'>
function loadFileAsText()
{
	var fileToLoad = document.getElementById("fileToLoad").files[0];

	var fileReader = new FileReader();
	fileReader.onload = function(fileLoadedEvent) 
	{
		var textFromFileLoaded = fileLoadedEvent.target.result;
		var texto = textFromFileLoaded;
		listar(texto);
	};
	fileReader.readAsText(fileToLoad, "UTF-8");
}
function listar(texto){
	var quantidade = document.getElementById("lista").rows.length;
	if (quantidade>1){
		for(var cont=1;cont<=quantidade;cont++){
			document.getElementById("lista").deleteRow(cont);
		}
	}
	var itens = texto.split('[item]');
	for(var i=1;i<itens.length;i++){
		var valores = itens[i].split("|");
		document.getElementById("lista").innerHTML +='<tr><div>'+valores[1]+'</div><div>'+valores[2]+'</div><div>'+valores[3]+'</div><div>'+valores[4]+'</div></tr>';
	}
}
</script>
</body>
</html>

Note that Chrome has a security system that does not allow reading files in physical directory, so I used Firefox for simulation tests.

I’m not getting any way that the browser shows the information without me having to upload the file (it was like this before I made the changes to the code).

Can anyone help me or direct me to some link that will help me accomplish this relatively simple task? I’ve tried debugging every way I know, inspecting by Chrome, checking the console errors, and what it shows is always the same error message, which you can see by clicking "run" right up here.

I would love to be able to do this using Javascript (no jQuery/Ajax).

Any suggestion on how to improve my question and my research is always welcome.

Thank you very much.

  • Run html? This phrase got weird... Another point: you’re working with a static file http server?

  • In that comment you mentioned knowing about Java. Why not use Java as a service to do this then? Then you will have access to a server of dynamic pages, which would make your life easier, not to mention that you would have the possibility to treat data the way you want, be with .txt, SQLite or other way of storing data

  • Execute html I understand as "open with the browser". Yes, I have knowledge in Javascript, but not much... That’s why I have so many doubts. I did the training at Khanacademy and I am trying to improve myself. Could you recommend me some site that contains a good training? Ah, I need to use javascript inside the html file, because I want to have all the website programming in one file. Thanks for the comment.

  • The lessons of Codecademy.com are really good worth taking a look

1 answer

2


You can store the information in a file json in the "static server" and query using the API Fetch which already returns a parsed json result for an object javascript(if there is a file with valid syntax)

Example:

// arquivo json no servidor (test.json)
{
    "fulano": "Chico",
    "Fulana": "Aninha"
}

// buscando os dados
fetch('./test.json').then((response)=>{
    if (response.ok) {
        return response.json(); // aqui retorna parseado para a promise subsequente
    }
    throw new Error('Resposta Invalida'); // aqui lança para o "catch"
}).then((dados)=>{
    // aqui dados já é um objeto javascript de test.json
    console.log(dados.fulano); // imprime: Chico
}).catch((error)=>{
    // trate a exceção ou erro aqui
});

As you can see is a basic example but you can structure a static bank in json better than plain text since fetch already converts into object you can go through arrays and do all checks normally.

Like fetch works with Promise if there is error will always fall into catch.


(editing) a more practical example:

json data.

[
    {
        "name": "Danilo",
        "cep": "13057423",
        "casas": [
           "1",
           "200"
        ]
    },
    {
        "name": "Denise",
        "cep": "13059778",
        "casas": [
           "200",
           "500"
        ]
    },
    {
        "name": "Guilherme",
        "cep": "13052445",
        "casas": [
           "500",
           "1000"
        ]
    }
]

index.html

<body>
    <div id="show-users"></div>

    <button id="sur">Mostrar usuários registrados</button>


    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        // variavel que irá receber a database
        var data;

        // button event
        $('#sur').on('click', function(event){
           event.preventDefault();
           // percorrer a database
           for (let i = 0; i < data.length; i++) {
                // mostrar usuários por nome
                $('#show-users').append('<span>'+data[i].name+'</span>';
           }
        });


        fetch('./dados.json').then((response)=>{
            if (response.ok) {
                return response.json();
            }
        }).then((dados)=>{
            /**
             * manipule o array de dados aqui ou sete uma variável pré-definida
            for (let i = 0; i < dados.length; i++) {
                 // sua lógica aqui
            }
            */
             data = dados; // atribuir para a variável "data"
        }).catch((e)=>{
            console.log(e);
        });
    </script>
</body>
  • Thank you for the answer. Could you point me to a site where you have some intermediate level tutorial for Javascrip/site automation?

  • I don’t understand what site automation refers to? Can you search for a reference to the Fetch API on MDN or on this blog Brasiljs.org which is very succinct

  • Can you tell us where you are posting your website? If it’s Github Pages or Gitlab Pages you can use git to update the database or even integrate msmo with an application Heroku

  • By site automation I mean letting it so that the user clicks on a button, automatically appears the file information. I’m performing everything on my own physical disk, without uploading to a server, what I’m trying to do is make the code recognize the file. txt which is next to . html, without having to upload to the system via a "choose file" button. When I get good at html and Javascript, I plan to open a site on a paid server such as godaddy etc. I’m currently just testing and studying.

  • 1

    Well, this "automation" is actually simply the implementation of programming logic. Once when loading your page the user interactions (say a click on a button) should be handled with javascript (like jQuery). If you use json you can load this database to a variable as soon as the page opens ( using fetch) and as user "click" handle the action (recover show desired result)

  • 1

    I did an update in the example, but basic is simple if you want to provide such interaction you should write the logic. I don’t know a tool, or framework that does this automatically. Good luck good study! Locally (by files) really hard... I recommend if you don’t have (or don’t use) a more robust local server use browser extensions ex: for Chrome

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.