Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda