Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

261
Visualizações
read text from file and keep in an array in

At the following code, I have the array of ["Saab", "Volvo", "BMW"].

<div>
    <span id="my-element" class=" css-1yy09vp" data-font-weight="semibold"></span>
    <script>
        const cars = ["Saab", "Volvo", "BMW"];
        const textElement = document.getElementById("text");
        function carDisplayer() {
            let i = 0;
            return function(cars) {
                let interval = setInterval(() => {
                    if (i < cars.length) {
                        textElement.textContent = cars[i];
                        i++;
                    } else {
                        clearInterval(interval);
                        i = 0;
                    }
                }, 10000);
            }
        }
        let displayCars = carDisplayer();
        displayCars(cars);
    </script>
</div>

I am interested in reading the content of the array from a text file instead of hardcoding. For example, if I have the following file;

Saab
Volvo
BMW

called "content.txt", how can I read the content and assign it as "cars" array?

Thanks,

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

1st option: Read online file

Online files can be read through AJAX methods such as XHR or fetch. The following code could be a solution but it's not working for files on the computer. The content.txt file must be beside the HTML file on the server.

More information about fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

<div>
  <span id="my-element" class="css-1yy09vp" data-font-weight="semibold"></span>
  <script>
  let cars = [];
  const textElement = document.getElementById("my-element");
  function carDisplayer() {
    let i = 0;
    return function(cars) {
      let interval = setInterval(() => {
        if (i < cars.length) {
           textElement.innerHTML = cars[i];
           i++;
        } else {
           clearInterval(interval);
           i = 0;
        }
      }, 1000);
    }
  }

  fetch("./content.txt").then(function(response) {
    response.text().then(function(text) {
      console.log(text);
      cars = text.split('\n');
      let displayCars = carDisplayer();
      displayCars(cars);
    });
  });       
  </script>
</div>

2nd option: Read from user computer

Reading a file from the user's computer is impossible until that user allows it. In the following code, user should browse the content.txt file, then the code will run.

Select Text File: <input type="file" id="file-select">
<div>  
  <span id="my-element" class="css-1yy09vp" data-font-weight="semibold"></span>
  <script>
  let cars = [];
  const textElement = document.getElementById("my-element");
  function carDisplayer() {
    let i = 0;
    return function(cars) {
      let interval = setInterval(() => {
        if (i < cars.length) {
           textElement.innerHTML = cars[i];
           i++;
        } else {
           clearInterval(interval);
           i = 0;
        }
      }, 1000);
    }
  }
  
  document.getElementById('file-select').onchange = function() {
    var reader = new FileReader();
    reader.onload = function(progressEvent){    
      console.log(this.result);
      cars = this.result.split('\n');  
      let displayCars = carDisplayer();
      displayCars(cars);
    };
    reader.readAsText(this.files[0]);
  };
  </script>
</div>
about 4 years ago · Juan Pablo Isaza Relatório

0

There are many options. Easiest is to store the JSON as separate file and save it as JS. The file will look like

var data = [{...}, {...}];

You will only load the file with <script src="./data.js"></script>.

If you will store it as json then it's bit harder and you need to get it with ajax. Easiest is to use fetch(). You will get the file, parse it and save it.

fetch('./data.json').then(data => JSON.parse(data)).then(data => callback(data));

To handle the async call will be up to you if you want to use callback in some async call or what you will need. This will handle it in browser. As it looks like you are not doing any SSR.

You can change your code to something like this:

<script>
    const textElement = document.getElementById("text");
    function carDisplayer() {
        let i = 0;
        return function(cars) {
            let interval = setInterval(() => {
                if (i < cars.length) {
                    textElement.textContent = cars[i];
                    i++;
                } else {
                    clearInterval(interval);
                    i = 0;
                }
            }, 10000);
        }
    }
    let displayCars = carDisplayer();
    fetch('./data.json').then(data => JSON.parse(data)).then(data => displayCars(data));
</script>
about 4 years ago · Juan Pablo Isaza Relatório

0

I'm assuming that you're using node.js. this could help you:

const readLine = require('readline');
const f = require('fs');
var file = './demo.txt';
var rl = readLine.createInterface({
    input : f.createReadStream(file),
    output : process.stdout,
    terminal: false
});
rl.on('line', function (text) {
 console.log(text);
});

Outline:

Line 1
Line 2
Line 3

Line 5

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda