yusuf
yusuf

Reputation: 3781

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,

Upvotes: 1

Views: 3215

Answers (4)

martin.malek
martin.malek

Reputation: 2218

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>

Upvotes: 4

Amirreza Noori
Amirreza Noori

Reputation: 1525

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>

Upvotes: 2

traynor
traynor

Reputation: 8667

fetch the txt file, extract data and pass the data to the interval function

      const textElement = document.getElementById("text");

      function carDisplayer(cars) {
        let i = 0;

          let interval = setInterval(() => {
            if (i < cars.length) {
              textElement.textContent = cars[i];
              i++;
            } else {
              clearInterval(interval);
              i = 0;
            }
          }, 10000);

      }


      fetch('/file.txt')
        .then(function(response) {
          response.text()
            .then(function(text) {
              console.log('res', text);
              let res = text.split('\n');
              cars = res;
              console.log(res);
              carDisplayer(res);
            });
        });

Upvotes: 0

nillabobillababolla
nillabobillababolla

Reputation: 44

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

Upvotes: 0

Related Questions