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

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

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 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