0

I have this script that I would like to extend in order to be able to use dozens of lines...

var arr = [
   { name:'Susan', country:'USA', age:27 },
   { name:'John', country:'Canada', age:34 },
   { name:'Klaus', country:'Germany', age:23 },
   { name:'Peter', country:'Greece', age:29 }
];
var template = document.querySelector('#tmplt');
for (var i = 0; i < arr.length; i++) {
    var user = arr[i];
    var clone = template.content.cloneNode(true);
    var h2 = clone.querySelectorAll('h2');
    h2[0].className = "username";
    h2[0].innerHTML = user.name;
    var p = clone.querySelectorAll('p');
    var div = clone.querySelectorAll('div');
    div[0].className = "box";
    p[0].className = "content";
    p[0].innerHTML = "Country: "+user.country+"<br>Age: "+user.age;
    template.parentNode.appendChild(clone);
}

Instead of putting all the users data in the script, I am trying to find a way to read them from a txt files. Can anyone help?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
MrCoder74
  • 40
  • 4
  • 1
    Does this answer your question? [How do I load the contents of a text file into a javascript variable?](https://stackoverflow.com/questions/196498/how-do-i-load-the-contents-of-a-text-file-into-a-javascript-variable) – Heretic Monkey Feb 17 '22 at 15:45
  • why exactly txt file? – adir abargil Feb 17 '22 at 15:49

1 Answers1

0

Instead of using a txt file it is better to use a json file like this:

users.json

[
   { name:'Susan', country:'USA', age:27 },
   { name:'John', country:'Canada', age:34 },
   { name:'Klaus', country:'Germany', age:23 },
   { name:'Peter', country:'Greece', age:29 }
]

if you are using node read the file like this:

var fs = require('fs');
var rawcontent = fs.readFileSync('./users.json','utf-8');
var users = JSON.parse(rawcontent)
console.log(users)

If you are running js on browser use fetch like this:

fetch('link to user.json')
   .then(res=>res.json())
   .then(data=>{
      console.log(data)
    })
JaivBhup
  • 792
  • 4
  • 7