Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
Read txt from file to array in JavaScript

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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)
    })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!